Set a models user field to the current logged in user before saving its django ModelForm

主宰稳场 提交于 2019-12-25 12:45:14

问题


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.


回答1:


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



回答2:


I use a variation on WoLph above:

def save(self, *args, **kwargs):
    # add defaut owner field if not already stated

    if 'owner' not in self.__dict__:
        self.creator = system_user()

    super(MyModel, self).save(*args, **kwargs)



回答3:


So answered my own question, use commit=false and modify whatever values you want. This code section draws in ideas from the two previous answers( wolPh and user*** )


def save(self,user, commit=True, *args, **kwargs):

    job = super(JobForm, self).save(commit=False,*args, **kwargs)
    job.owner = user
    if commit:
        job.save()
    return job



来源:https://stackoverflow.com/questions/4425150/set-a-models-user-field-to-the-current-logged-in-user-before-saving-its-django-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!