且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在保存其django ModelForm之前,将模型用户字段设置为当前登录的用户

更新时间:2023-12-04 09:21:28

我总是覆盖 save()方法并添加一个用户。



像这样:

 类JobForm(ModelForm):
def save(self,user,commit = True):
job = ModelForm。 save(commit = False)
job.owner = user
如果提交:
job.save()
返回作业
pre>

i have a model form as so below

class JobForm(ModelForm):
    class Meta:
        model = Job
        exclude = ('date_added', 'date_modified','owner','status','tags','slug','winning_tech','completiondate')

The owner field is a foreignKey linked to the Django User model and it's excluded from being rendered in the form. I am trying to set the owner field to the current logged in user before i save the form. My save function is contained in the following code.


def createJob(request):
  bix_user=getBixUser(request.user)
  if request.method == 'POST':
      form = JobForm(request.POST)
      form.fields['owner']=bix_user
      if form.is_valid():
         form.save()

      return HttpResponseRedirect('/home')
 else:
        ....

I am very sure that i am doing the wrong thing. I have not been in touch with my django side for a while so i would appreciate any help.

I always overwrite the save() method and add a user to it.

Something like this:

class JobForm(ModelForm):
    def save(self, user, commit=True):
        job = ModelForm.save(commit=False)
        job.owner = user
        if commit:
            job.save()
        return job