Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 792
sgarza62 Avatar asked Oct 11 '12 21:10

sgarza62


People also ask

What does form Save () do in Django?

form. save() purpose is to save related model to database, you are right. You're also right about set_password , for more info just read the docs. Django knows about model and all it's data, due to instance it's holding (in your case user ).

How do I save models in Django?

The save method is an inherited method from models. Model which is executed to save an instance into a particular Model. Whenever one tries to create an instance of a model either from admin interface or django shell, save() function is run.


2 Answers

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.

like image 116
dokkaebi Avatar answered Sep 21 '22 12:09

dokkaebi


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() 
like image 41
dani herrera Avatar answered Sep 22 '22 12:09

dani herrera