How to make a single form for two related models?

87 views Asked by At

I have 2 models, one is a User models and other is a profile model. Now I want to make a single form the validates and saves the data during registration.

I have got both the forms in a single form tag and my view receives the data via request.POST, but how do I get the form validation to work?

Here is my view -

class IndexView(TemplateView):
    template_name = 'index.html'
    register_form = RegistrationForm(instance=User())
    broker_profile_form = BrokerProfileForm(instance=BrokerProfile())

    def get(self, request, *args, **kwargs):
        user_type_form = UserTypeForm()


        return render(request, self.template_name,
                      {
                       'login_form': self.register_form,
                       'broker_profile_form': self.broker_profile_form,
                      }
        )


    def post(self, request, *args, **kwargs):
        print 'post data'
        print request.POST
        print self.register_form.is_valid()
        for field in self.register_form:
            print field.errors
1

There are 1 answers

2
Sylvain Biehler On

First, read this answer to a similar question : https://stackoverflow.com/a/2374240/4789005 and use prefix

Second, when the view is hit with post you should get the form from the request. If not, you will never get the data from the request.

Class IndexView(TemplateView):
    template_name = 'index.html'

    def get(self, request, *args, **kwargs):
        form1 = MyFormClass(prefix='some_prefix_1')
        form2 = MyFormClass(prefix='some_prefix_2')
        return render(request, self.template_name,
                      {
                       'form1': form1,
                       'form2': form2
                      }
        )


    def post(self, request, *args, **kwargs):
        form1 = MyFormClass(request.POST, prefix='some_prefix_1')
        for field in form1:
            ...