Home > Enterprise >  Django form_valid method
Django form_valid method

Time:05-08

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)

CodePudding user response:

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.

  • Related