2013-06-18 97 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 –

相關問題