Search code examples
pythondjangodjango-modelsdjango-formsmodelform

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?

Can you provide hypothetical situations where this might be useful?


Solution

  • 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's the documentation on the save method. Note that if your form includes many-to-many fields, you'll also want to call form.save_m2m() after saving the model instance.