Django form_valid method

Issue

In my form’s view I wonder what if I don’t add product_form.save method in the code below and what if I add that:

def form_valid(self, form):
        product_form = form.save(commit=False)
        product_form.user = self.request.user
        product_form.save() # what if I delete this?
        return super().form_valid(form)

Solution

In what view do you use this? If it is a CreateView [Django-doc] or UpdateView [Django-doc], it is fine. For a (simple) FormView [Django-doc], it is not since a FormView does not save the form.

You however do not need to save the form with commit=False to retrieve the instance. A simple one-liner to set the user is:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import CreateView

class MyCreateView(LoginRequiredMixin, CreateView):
    # …
    
    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

The name product_form in product_form = form.save(commit=False) is also somewhat misleading: the .save() method does not return a Form, but a Product object, hence it is a Product. But you do not need to save that product in the database, since a CreateView and UpdateView will call the .save() function of the form to save the model together with many-to-many relations that are specified in the form.

Answered By – Willem Van Onsem

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published