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

查看:34
本文介绍了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.

推荐答案

您可以使用 CreateWithInlinesViewrel="nofollow noreferrer">django-extra-views.代码如下所示:

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天全站免登陆