Django ModelForm: what is persistence used for (commit = False)?

Why would I ever use save(commit=False) instead of creating a form object from a subclass of ModelForm and run is_valid() to validate both the form and the model?

In other words, what is save(commit=False) for?

If you don't mind, could you guys provide hypothetical situations where this might be helpful?

+42
django django-models django-forms
Oct 11
source share
4 answers

This is useful when you get most of your model data from a form, but you need to fill in some of the null=False fields with informal data.

Saving with commit = False provides you with a model object, then you can add your extra data and save it.

This is a good example of this situation.

+54
Oct 11
source share

Here is the answer ( from the docs ):

 # Create a form instance with POST data. >>> f = AuthorForm(request.POST) # Create, but don't save the new author instance. >>> new_author = f.save(commit=False) 

The most common situation is getting an instance from the form, but only "in memory", and not in the database. Before saving, you want to make some changes:

 # Modify the author in some way. >>> new_author.some_field = 'some_value' # Save the new instance. >>> new_author.save() 
+19
Oct 11
source share

In the Django docs:

This save () method accepts an optional commit keyword argument that accepts either True or False. If you call save () with commit = False, then it will return an object that has not yet been saved to the database.

In this case, you need to call save () on the resulting instance of the model. This is useful if you want to perform custom processing of an object before saving it, or if you want to use one of the specialized options for saving the model. commit defaults to True.

It seems that save (commit = False) creates an instance of the model that it returns to you. Which is neat for some post-processing before actually storing it!

+5
Oct 11
source share

As a β€œreal-world example,” consider a user model in which the email address and username always match, and then you can overwrite the ModelForm save method, for example:

 class UserForm(forms.ModelForm): ... def save(self): # Sets username to email before saving user = super(UserForm, self).save(commit=False) user.username = user.email user.save() return user 

If you did not use commit=False to set the username to the email address, you will either have to change the way the user model is saved, or save the user object twice (which duplicates the expensive database operation.)

+4
Jun 14 '16 at 19:27
source share



All Articles