[Django]-Using request.user with Django ModelForm

46๐Ÿ‘

โœ…

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

๐Ÿ‘คDaniel Roseman

9๐Ÿ‘

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()
๐Ÿ‘คmatino

4๐Ÿ‘

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.

๐Ÿ‘คmelbic

0๐Ÿ‘

If you are using ModelAdmin
you should add method get form on your ModelAdmin

class BlogPostAdmin(admin.ModelAdmin):
    form = BlogPostForm

    def get_form(self, request, **kwargs):
        form = super(BlogPostAdmin, self).get_form(request, **kwargs)
        form.request = request
        return from

and you can now access request in your ModelForm

class ProductAdminForm(forms.ModelForm):
    
    def save(self, commit: bool,  *args, **kwargs):
        self.instance.user = self.request.user
        return super().save(commit=commit)
        pass

Leave a comment