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?
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 ).
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With