Django:使用CreateView创建两个模型

Jac*_*nta 0 django django-forms

我有一个用于创建客户的CreateView,但我还需要与该客户一起创建"标识"模型.我有一个识别模型,它具有模型的外键,因为我们需要能够为某些ID添加任何数量的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
Run Code Online (Sandbox Code Playgroud)

CustomerInformationForm是ModelForm.我想为标识创建另一个ModelForm,但我不知道如何将第二个表单添加到CreateView.我找到了这篇文章,但它已经有5年了,并没有谈到CreateView.

Ant*_*ets 7

你可以使用CreateWithInlinesViewDjango的额外意见.代码如下所示:

from extra_views import CreateWithInlinesView, InlineFormSet


class IdentificationInline(InlineFormSet):
    model = Identification


class CustomerCreationView(CreateWithInlinesView):
    model = CustomerInformation
    inlines = [IdentificationInline]
Run Code Online (Sandbox Code Playgroud)