如何在单个formView类Django中验证多个表单

时间:2015-12-13 13:08:28

标签: django django-models django-templates django-views django-class-based-views

我有一个formView课程,如下所示: -

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 

在我的模板thread.html中,我有两个模型但只有一个提交按钮。问题是我无法从second_form获取任何数据,也无法验证second_form。我正在接收来自form但未来自second_form的数据。谁能告诉我如何验证second_form数据。谢谢

一种方法是使用request.post['data']但是还有其他任何方法吗?

1 个答案:

答案 0 :(得分:4)

我使用FormView(或CreateViewUpdateView等) 这就是我的工作:

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