问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/34251412/how-to-validate-mulitple-forms-in-a-single-formview-class-django