Using request.user with Django ModelForm

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.)

Leave a Comment