Simple Method of Updating Models with ModelForms

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:

1
2
3
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:

1
2
3
4
5
6
7
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?

1
2
3
4
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.

comments powered by Disqus