Using request.user with Django ModelForm

混江龙づ霸主 提交于 2019-11-27 20:09:39
Daniel Roseman

You just need to exclude it from the form, then set it in the view.

class AnimalForm(ModelForm):
    class Meta:
        model = Animal
        exclude = ('publisher',)

... and in the view:

    form = AnimalForm(request.POST)
    if form.is_valid():
        animal = form.save(commit=False)
        animal.publisher = request.user
        animal.save()

(Note also that the first else clause - the lines immediately following the redirect - is unnecessary. If you leave it out, execution will fall through to the two lines at the end of the view, which are identical.)

Another way (slightly shorter):
You need to exclude the field as well:

class AnimalForm(ModelForm):
    class Meta:
        model = Animal
        exclude = ('publisher',)

then in the view:

animal = Animal(publisher=request.user)  
form = AnimalForm(request.POST, instance=animal)
if form.is_valid():
     animal.save()

I would add it directly to the form:

class AnimalForm(ModelForm):
    class Meta:
        model = Animal
        exclude = ('publisher',)

    def save(self, commit=True):
        self.instance.publisher = self.request.user
        return super().save(commit=commit)

This is in my opinion the cleanest version and you may use the form in different views.

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