我正在构建一个带有 2 个表单的 TemplateView,一个允许用户选择客户 (CustomerForm),另一个允许用户为客户添加订单 (OrderForm)。
代码:
class DisplayOrdersView(TemplateView):
template_name = 'orders/orders_details_form.html'
def get_context_data(self, **kwargs):
context = kwargs
context['shippingdetailsform'] = ShippingDetailsForm(prefix='shippingdetailsform')
context['ordersform'] = OrdersForm(prefix='ordersform')
return context
def dispatch(self, request, *args, **kwargs):
return super(DisplayOrdersView, self).dispatch(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def post(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
profile=request.user.get_profile()
if context['shippingdetailsform'].is_valid():
instance = context['shippingdetailsform'].save(commit=False)
instance.profile = profile
instance.save()
messages.success(request, 'orders for {0} saved'.format(profile))
elif context['ordersform'].is_valid():
instance = ordersform.save(commit=False)
shippingdetails, created = shippingdetails.objects.get_or_create(profile=profile)
shippingdetails.save()
instance.user = customer
instance.save()
messages.success(request, 'orders details for {0} saved.'.format(profile))
else:
messages.error(request, 'Error(s) saving form')
return self.render_to_response(context)
首先,我似乎无法将任何现有数据加载到表单中。假设 UserProfile->ShippingDetails (fk:UserProfile)->Orders (fk:ShippingDetails) 之间存在一对一的关系,如何在加载时将适当的变量查询到表单中?
另外,如何保存数据?保存时会引发错误,我无法检索有用的调试信息。
我的方法对于在模板视图中有多个表单是否正确?