Django:使用CreateView创建两个模型 [英] Django: Create two models with a CreateView

查看:849
本文介绍了Django:使用CreateView创建两个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CreateView来创建一个客户,但是我也需要和这个客户一起创建一个识别模型。我有一个身份识别模型,具有模型的外键,因为我们需要能够添加任何数量的ID(驾驶执照,护照等)

I have a CreateView for creating a customer, but I also need to create an 'identification' model along with this customer. I have an identification model that has a foreign key to the model because we need to be able to add any amount of IDs to some (Drivers license, Passport, etc)

无论如何,当前的代码(仅创建一个新客户)如下所示:

Anyways, the current code (Which only creates a new customer) looks like this:

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。

CustomerInformationForm is ModelForm. I would like to create another ModelForm for Identifications, but I do not know how to add the second form to a CreateView. I found this article, but it is 5 years old and not talking about a CreateView.

推荐答案

如果有人有同样的问题。您可以使用 django-extra-views 中的CreateWithInlinesView。代码如下所示:

In case anyone else has the same question. You could use CreateWithInlinesView from django-extra-views. The code would look like this:

from extra_views import CreateWithInlinesView, InlineFormSet


class IdentificationInline(InlineFormSet):
    model = Identification


class CustomerCreationView(CreateWithInlinesView):
    model = CustomerInformation
    inlines = [IdentificationInline]

这篇关于Django:使用CreateView创建两个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆