Handling two Django models in a single POST

There are times when, you want to handle multiple Django models in a single POST request (By this i meant data posted from html form/ template contains data of two different Django models). I was struggling with this few months back and got a fantastic reference link from #django on IRC.

You can use the below method as a simple example, here’s a view that updates a User and their Profile in one view:

def user_edit(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=request.user)
        profile_form = ProfileForm(request.POST, instance=request.user.profile)

        if all([user_form.is_valid(), profile_form.is_valid()]):
            user = user_form.save()
            profile = profile_form.save()
            return redirect(user)
    else:
        user_form = UserForm(instance=request.user)
        profile_form = ProfileForm(instance=request.user.profile)

    return render(request, 'user_form.html', {
            'user_form': user_form,
            'profile_form': profile_form,
            })

The two most important things to notice here are:

a. The use of all() instead of user_form.is_valid() and profile_form.is_valid().

This is because Python will skip the if clause if the first form is not valid, and so it won’t run validation on the second form. If some error is present in second from user will again get the error second time. using all() runs validation on all the submitted forms thus you get the errors at one time.

b. Two forms in the context.

Just render them all inside the one <form> tag, and it will be fine. If any of the field names clash, pass a prefix= when constructing one of the forms, to prefix its field names so they’re unique.

Related blogs :

  1. Django – AttributeError: ‘Http404’ object has no attribute ‘status_code’
  2. Make primary key with two or more field in Django

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s