2013-06-18 189 views
0

我有创建用于创建客户的CreateView,但我还需要与此客户一起创建“识别”模型。我有一个识别模型,它有一个模型的外键,因为我们需要能够为一些(驾照,护照等)添加任意数量的IDDjango:使用CreateView创建两个模型

总而言之,当前的代码(只创建一个新的客户)看起来像这样:

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。我发现this article,但它是5岁,并没有谈论一个CreateView。

回答

-1
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 

我认为应该工作..我的工作,我无法测试它..

+0

但是,当您执行POST时,它只创建CustomerInformationForm,而不是另一个。 – lalo

+0

你必须添加一个自定义的“def post(自我,请求,* args,** kwargs):”这需要你的表单并保存数据 –

5

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

from extra_views import CreateWithInlinesView, InlineFormSet 


class IdentificationInline(InlineFormSet): 
    model = Identification 


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

我通常不喜欢向“第三方”这个,但我看了一下这个以及其他几个django-extra-views提供的东西,它看起来像一个非常漂亮的包。 +1 –

相关问题