Simple Method of Updating Models with ModelForms

Posted by Chris Bartos on Feb 8, 2019

Maybe you’re new at using Django and you’re just starting to get familiar with the ModelForm.

Let’s say you have a ModelForm for a Customer that looks like this:

class CustomerForm(forms.Form):
    name = forms.CharField(max_length=100)
    email = forms.EmailField(max_length=100)

You then put this form on a template and render it out so your users can fill it out and update their information. When your user submits the form, what does your View look so that your can update their information?

Maybe, you’re thinking that you can do something like this:

customer = get_object_or_404(Customer, pk=id)
customer_form = CustomerForm(request.POST)
if custom_form.is_valid():
	customer = customer_form.save(commit=False)
	customer.name = customer.name
	customer.email = customer.email
	customer.save()
  • Essentially, what you’re trying to do is see if the user exists
  • So you grab the customer from the database.
  • You get the CustomerForm with the request.POST data.
  • After, you try saving the form with commit=False which prevents the data from being saved to the database.
  • And at the very end, you update the customer variable that you got from the database with what’s in the form.

That’s okay to do if you’re new to ModelForm and it’s explicit in what you are trying to do which might make it easy to read. However, this isn’t how you do it with Django. There is a MUCH easier way. Ready?

customer = get_object_or_404(pk=id)
form = CustomerForm(request.POST, instance=customer)
if form.is_valid():
	form.save()

Easy? You can read more about ModelForms from this part of the documentation (especially if you have much more complex forms). Next time you’re working with ModelForms, try this simple way of updating model data.


Similar Posts

What do you do when 'makemigrations' is telling you About your Lack of Default Value
How to Implement Many-To-Many Relationship in Django
Test your Queries before they make it into Production using the Django Shell
I have a ChoiceField Callable that Includes a Queryset but it Breaks my Django app
How to filter a DateTimeField by today's date in Django

Need help with Django REST Framework? Django REST Framework documentation a little confusing?

Join me for my FREE Django REST Framework email course:

Django REST Framework Email Course

You'll get 1 lesson everyday for 7 days.
You'll learn:

  • Serializers
  • Request Methods
  • Endpoints
  • Basic Authentication
  • JQuery Integration
  • AngularJS Integration
Powered by ConvertKit