我有一个用于创建客户的 CreateView,但我还需要与该客户一起创建一个“识别”模型。我有一个识别模型,该模型具有外键,因为我们需要能够向某些模型(驾驶执照、护照等)添加任意数量的 ID
无论如何,当前代码(仅创建一个新客户)如下所示:
class CustomerCreationView(CreateView):
template_name = "customers/customer_information.html"
form_class = CustomerInformationForm
def get_context_data(self, *args, **kwargs):
context_data = super(CustomerCreationView, self).get_context_data(*args, **kwargs)
context_data.update({
'new_customer': True,
})
return context_data
CustomerInformationForm 是 ModelForm。我想为标识创建另一个 ModelForm,但我不知道如何将第二个表单添加到 CreateView。我找到了这篇文章,但它已经有 5 年历史了,而且没有讨论 CreateView。
您可以使用
django-extra-views中的
CreateWithInlinesView
。代码如下所示:
from extra_views import CreateWithInlinesView, InlineFormSet
class IdentificationInline(InlineFormSet):
model = Identification
class CustomerCreationView(CreateWithInlinesView):
model = CustomerInformation
inlines = [IdentificationInline]
class CustomerCreationView(CreateView):
template_name = "customers/customer_information.html"
form_class = CustomerInformationForm
other_form_class = YourOtherForm
def get_context_data(self, *args, **kwargs):
context_data = super(CustomerCreationView, self).get_context_data(*args, **kwargs)
context_data.update({
'new_customer': True,
'other_form': other_form_class,
})
return context_data
class CustomerCreationView(CreateView):
template_name = "customers/customer_information.html"
form_class = CustomerInformationForm
def get_context_data(self, *args, **kwargs):
context_data = super(CustomerCreationView, self).get_context_data(*args, **kwargs)
context_data["yournewform"] = YourNewForm(self.request.POST or None, self.request.FILES or None)
return context_data
def post(self, request, *args, **kwargs):
form = self.get_form()
yournewform = YourNewForm(request.POST, request.FILES)
if form.is_valid() and yournewform.is_valid():
'''
# this is just example, you can change according to your model and form
user = YourNewForm.save(commit=False)
user.set_password(user.password)
user.roll = 'parent'
user.save()
parent = form.save(commit=False)
parent.user = user
parent.save()
messages.success(request, "Parent Created successfully")
return redirect("parents")
'''
else:
return render(request, self.template_name, {"form":form, "yournewform":yournewform})