1

I have a formView class as you can see below:-

view.py

class ThreadForm(FormView):
        template_name = 'thread.html'
        form_class = ThreadModelForm
        success_url = '/success'

        def form_valid(self, form):
            # This method is called when valid form data has been POSTed.
            # It should return an HttpResponse.
            print form.cleaned_data
            return super(ThreadForm, self).form_valid(form)

        def get_context_data(self, **kwargs):
            context = super(ThreadForm, self).get_context_data(**kwargs)
            context['second_form'] = MessageModelForm
            return context

thread.html

{form.as_p}
{second_form.as_p}
SUBMIT 

In my template thread.html, I have two modelforms but single submit button. The problem is I am not getting any data from my second_form and not able validate second_form as well. I am receiving data from form but not from second_form. Could anyone tell me how to validate second_form data. Thank you

One method is to use request.post['data'] but is there any other method there?

python
  • 4,403
  • 13
  • 56
  • 103

1 Answers1

5

I do use FormView (or CreateView, UpdateView, etc.) This is what I do:

class ThreadForm(FormView):
    template_name = 'thread.html'
    form_class = ThreadModelForm
    ...

    def get_second_form(self):
       # logic to construct second form goes here
       # if self.request.method == 'POST' you need to pass self.request.POST
       # to the form. Add whatever you need to create the form
       if self.request.method == 'POST':
          return SecondForm(self.request.POST)
       else:
          return SecondForm()

    def form_valid(self, form):
        self.second_form = self.get_second_form()
        if self.second_form.is_valid():
            # All good logic goes here, which in the simplest case is
            # returning super.form_valid
            return super(ThreadForm, self).form_valid(form)
        else:
            # Otherwise treat as if the first form was invalid
            return super(ThreadForm, self).form_invalid(form)

    # Do this only if you need to validate second form when first form is
    # invalid
    def form_invalid(self, form):
        self.second_form = self.get_second_form()
        self.second_form.is_valid()
        return super(ThreadForm, self).form_invalid(form)

    # Trick is here
    def get_context_data(self, **kwargs):
        context = super(ThreadedForm, self).get_context_data(**kwargs)
        context['second_form'] = getattr(self, 'second_form', self.get_second_form())
        return context
Lorenzo Peña
  • 2,225
  • 19
  • 35
  • I solved the issue by extracting data from `request.POST` but your answer is much better. I will try this, and get back to you. – python Dec 14 '15 at 19:51