Saving ModelForm Data
Saving a New Instance
Calling save() on a valid, unbound-to-instance ModelForm creates a brand new database row.
Example: Saving a New Instance
Calling save() on a valid, unbound-to-instance ModelForm creates a brand new database row.
form = ArticleForm(request.POST)
if form.is_valid():
form.save()
{# Django-only code -- models.py/views.py/urls.py/settings.py
snippets, or template markup using Django template tags/variables
-- can't run standalone via Judge0 or the browser preview, since
it needs a real Django project. Only this course's pure-Python
examples (example_lang == 'python', no Django imports) are
actually runnable, so those still get the button below. #}
Updating an Existing Instance
Passing instance=article binds the form to an existing row, so save() updates it instead of creating a new one.
Example: Updating an Existing Instance
Passing instance=article binds the form to an existing row, so save() updates it instead of creating a new one.
form = ArticleForm(request.POST, instance=article)
if form.is_valid():
form.save()
{# Django-only code -- models.py/views.py/urls.py/settings.py
snippets, or template markup using Django template tags/variables
-- can't run standalone via Judge0 or the browser preview, since
it needs a real Django project. Only this course's pure-Python
examples (example_lang == 'python', no Django imports) are
actually runnable, so those still get the button below. #}
Delaying the Save
commit=False returns the model instance without writing to the database yet, letting you set extra fields first.
Example: Delaying the Save
commit=False returns the model instance without writing to the database yet, letting you set extra fields first.
form = ArticleForm(request.POST)
if form.is_valid():
article = form.save(commit=False)
article.author = request.user
article.save()
{# Django-only code -- models.py/views.py/urls.py/settings.py
snippets, or template markup using Django template tags/variables
-- can't run standalone via Judge0 or the browser preview, since
it needs a real Django project. Only this course's pure-Python
examples (example_lang == 'python', no Django imports) are
actually runnable, so those still get the button below. #}
- Calling form.save() without first checking form.is_valid(), which raises an error on invalid data.
- Assuming form.save() always writes to the database, even when commit=False was passed.
- Forgetting to set extra fields (like the logged-in user) on the instance before the final save() when using commit=False.
- A valid ModelForm's save() method creates or updates a model instance and writes it to the database in one call.
- Passing commit=False returns the unsaved instance so you can set extra fields before saving.
- Always call is_valid() before save() — saving an invalid form raises an error.
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: