Django:使用CreateView创建两个模型
我有一个用于创建客户的CreateView,但我还需要与此客户一起创建一个“标识”模型。我有一个识别模型,该模型有一个外键,因为我们需要能够向一些驾驶执照、护照等添加任意数量的ID 不管怎么说,当前只创建新客户的代码如下所示:Django:使用CreateView创建两个模型,django,django-forms,Django,Django Forms,我有一个用于创建客户的CreateView,但我还需要与此客户一起创建一个“标识”模型。我有一个识别模型,该模型有一个外键,因为我们需要能够向一些驾驶执照、护照等添加任意数量的ID 不管怎么说,当前只创建新客户的代码如下所示: class CustomerCreationView(CreateView): template_name = "customers/customer_information.html" form_class = CustomerInformationFo
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
from extra_views import CreateWithInlinesView, InlineFormSet
class IdentificationInline(InlineFormSet):
model = Identification
class CustomerCreationView(CreateWithInlinesView):
model = CustomerInformation
inlines = [IdentificationInline]
CustomerInformationForm是ModelForm。我想为标识创建另一个模型表单,但我不知道如何将第二个表单添加到CreateView。我发现了,但它已经5年了,而且还没有提到CreateView
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
我认为那应该行得通。。我正在工作,无法测试它。您可以使用CreateWithInlinesView。代码如下所示:
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
from extra_views import CreateWithInlinesView, InlineFormSet
class IdentificationInline(InlineFormSet):
model = Identification
class CustomerCreationView(CreateWithInlinesView):
model = CustomerInformation
inlines = [IdentificationInline]
但是,当你发帖子时,它只创建CustomerFormation表单,而不是另一个表单。你必须添加一个自定义的def postself、request、*args、**kwargs:这会采用你的表单并保存数据。我通常不喜欢向第三方求助于像这样的小事,但我看了一下django extra View提供的其他一些东西,它看起来是一个非常好的包裹+1.