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

Why would I ever use save(commit=False) instead of just creating a form object from the ModelForm subclass and running is_valid() to validate both the form and 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 useful?


That's useful when you get most of your model data from a form, but you 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!


As a "real example", consider a user model where the email address and the username are always the same, and then you could overwrite your ModelForm's save method like:

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 didn't use commit=False to set the username to the email address, you'd either have to modify the user model's save method, or save the user object twice (which duplicates an expensive database operation.)


            form = AddAttachmentForm(request.POST, request.FILES)
            if form.is_valid():
                attachment = form.save(commit=False)
                attachment.user = student
                attachment.attacher = self.request.user
                attachment.date_attached = timezone.now()
                attachment.competency = competency
                attachment.filename = request.FILES['attachment'].name
                if attachment.filename.lower().endswith(('.png','jpg','jpeg','.ai','.bmp','.gif','.ico','.psd','.svg','.tiff','.tif')):
                    attachment.file_type = "image"
                if attachment.filename.lower().endswith(('.mp4','.mov','.3g2','.avi','.flv','.h264','.m4v','.mpg','.mpeg','.wmv')):
                    attachment.file_type = "video"
                if attachment.filename.lower().endswith(('.aif','.cda','.mid','.midi','.mp3','.mpa','.ogg','.wav','.wma','.wpl')):
                    attachment.file_type = "audio"
                if attachment.filename.lower().endswith(('.csv','.dif','.ods','.xls','.tsv','.dat','.db','.xml','.xlsx','.xlr')):
                    attachment.file_type = "spreasheet"
                if attachment.filename.lower().endswith(('.doc','.pdf','.rtf','.txt')):
                    attachment.file_type = "text"
                attachment.save()

here is my example of using save(commit=False). I wanted to check what type of file a user uploaded before saving it to the database. I also wanted to get the date it was attached since that field was not in the form.