I'm unable to understand the reason why we use form.save(commit=False)
instead of simply using form.save()
in Django Views. Could someone explain me the difference and the necessities on both?

- 22,221
- 10
- 124
- 129

- 63
- 1
- 6
-
You can check this link: https://stackoverflow.com/a/12848678/11094356 – Pragya Sriharsh Apr 24 '19 at 07:32
2 Answers
form.save(commit=False)
is mostly used if you are working with ModelForm
.
The main use case is if you have a ModelForm
that doesn't contain all the required fields of a model. You need to save this form in the database, but because you didn't give it all the required fields, you will get an error. So the solution will save the form with commit=False
and then you can manually define the required values and then call the regular save.
The main difference is commit=False
will not push the changes in the database, but it will create all the structure needed for it. You will have to trigger the regular save later or otherwise your form will not be saved in the database.
For example:
# Creates a Dog class with all fields as mandatory:
class Dog(models.Model):
name = models.CharField(max_length=50)
race = models.CharField(max_length=50)
age = models.PositiveIntegerField()
# Creates a ModelForm with only name and age:
class DogForm(forms.ModelForm):
class Meta:
model = Dog
fields = ['name', 'age']
# In your view use this form:
def dog_view(request):
...
form = DogForm(request.POST or None)
# If the form is valid we need to add a race, otherwise we will get an error:
if form.is_valid():
dog = form.save(commit=False)
# Define the race here:
dog.race = 'Labrador retriever'
# And then do the regular save to push the change in the database:
dog.save()
...
Another example is the case when you want to deal manually with many to many relationships. The list of examples are long, but to make it short, it's when you need to take intermediate step before saving a Model
in the database.
-
1thankyou....... and i clearly understand the differences Class Dog and DogForm why we use commit = False – Abhishek Kumar May 15 '19 at 09:11
I haven't used save(commit=False) in Django View but I have used it in Django Admin to customize the submitted inline objects in Django Admin because if I use save()
equavalent to save(commit=True)
, more queries are run to customize the submitted inline objects in Django Admin.
You can see my answer explaining about save(commit=False)
vs save()
and how to customize the submitted inline objects in Django Admin.

- 22,221
- 10
- 124
- 129