Django ModelForm: What is save(commit=False) used for?

That's useful when you get most of your model data from a form, but need to populate some null=False fields with non-form data.

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

This is a good example of that situation.


Here it is the answer (from 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 to get the instance from form but only 'in memory', not in database. Before save it 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()

From the Django docs:

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

In this case, it's up to you to call save() on the resulting model instance. This is useful if you want to do custom processing on the object before saving it, or if you want to use one of the specialized model saving options. commit is True by default.

It seems that save( commit=False ) does create a model instance, which it returns to you. Which is neat for some post processing before actually saving it!