Chris
Chris

Reputation: 4983

How to combine 2 forms for use on the same page?

I have a UserProfile model to add extra metadata around the standard Django User model. I am creating a registration page, and I want the user to input both the basic user information captured in the User model as well as the general profile information captured in the UserProfile model.

How can we capture and validate both of these models in one request in Django, presumably through forms?

Upvotes: 0

Views: 69

Answers (1)

GAEfan
GAEfan

Reputation: 11360

There is valid debate about whether to keep the User and UserProfile separated. If you want to use separate classes:

@csrf_protect
def register(request, extra_context=None):
    if request.method == 'POST':

        user_form = AddUserForm(data=request.POST, files=request.FILES)
        user_profile_form = AddUserProfileForm(data=request.POST, files=request.FILES)

        if user_form.is_valid() and user_profile_form.is_valid():
            new_user = user_form.save(request.get_host())
            new_user_profile = user_profile_form.save(request.get_host(), new_user)
            return HttpResponseRedirect(reverse('registration_complete'))
    else:
        user_form = AddUserForm()
        user_profile_form = AddUserProfileForm()

    context = {}
    return render_to_response('registration_form.html',
                            {   'user_form': user_form,
                                'user_profile_form': user_profile_form },
                            context_instance=context)  

Upvotes: 1

Related Questions