0

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
utkbansal
  • 2,787
  • 2
  • 26
  • 47

1 Answers1

0

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:
            ...
Community
  • 1
  • 1
Sylvain Biehler
  • 1,403
  • 11
  • 25
  • Yes I have done this, I am able to access the post data, I am also able to save it. But I am unable to send back the error messages if any. – utkbansal Jun 10 '15 at 09:45
  • I am not sure of your problem then. Is it form validation https://docs.djangoproject.com/en/1.8/ref/forms/validation/#form-field-default-cleaning ? – Sylvain Biehler Jun 10 '15 at 09:48