我有2个型号,一个是用户型号,另一个是型材型号。现在我想在验证过程中创建一个单独的表格并保存数据。
我在两个表单标签中都有表单,我的视图通过request.POST接收数据,但是如何让表单验证工作?
以下是我的观点 -
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
答案 0 :(得分:0)
首先,请阅读类似问题的答案:https://stackoverflow.com/a/2374240/4789005并使用前缀
第二次,当使用post
点击视图时,您应该从请求中获得form
。如果没有,您将永远不会从请求中获取数据。
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:
...