2016-09-21 9 views
1

私はモデルの顧客とアドレスとDjangoの1.9でアプリケーションを構築しています:入れ子モデル用のフォームを作成するにはどうすればいいですか?

class Customers(models.Model): 
    name = models.CharField(db_column='NAME', max_length=400) 
    email = models.CharField(db_column='EMAIL', max_length=255, unique=True) 
    phone_number = models.CharField(db_column='PHONE_NUMBER', max_length=200, blank=True, null=True) 
    address = models.ForeignKey(Addresses, db_column='ADDRESS_ID', related_name='customer_address', null=True) 

class Addresses(models.Model): 
    street = models.TextField(db_column='STREET', max_length=2000) 
    city = models.CharField(db_column='CITY', max_length=400, blank=True, null=True) 
    postal_code = models.CharField(db_column='POSTAL_CODE', max_length=200, blank=True, null=True) 
    country = models.ForeignKey(Country, db_column='COUNTRY_ID', null=True) 

私はジャンゴで新しいですので、これはあまりにも多くのミスを持っている場合はご容赦ください。

私は、フォームを使用して新しい顧客を作成します:

class CustomersForm(ModelForm): 
    name = forms.CharField(label=_(u'Name'), widget=TextInput()) 
    email = forms.CharField(label=_(u'Email'), widget=TextInput()) 
    phone_number = forms.IntegerField(label=_(u'Phone Number'), required=False, widget=TextInput(attrs={'style': 'width:80px'})) 

をしかし、私はまだアドレスを追加できるようにしたいです。私はネストされたフォームについていくつかのものを読んでいましたが、私は理解しませんでした。

名前、メールアドレス、電話番号、住所を持つ顧客を作成するフォームを作成する際に助けてください。

答えて

0

私はそれを理解しました! :)

フォームのsaveメソッドをオーバーライドする必要があります。

class CustomersForm(ModelForm): 

    name = forms.CharField(label=_(u'Name'), widget=TextInput()) 
    email = forms.CharField(label=_(u'Email'), widget=TextInput()) 

    a_street = forms.CharField(label=_(u'Street'), widget=TextInput(), required=False) 
    a_postal_code = forms.CharField(label=_(u'Postal Code'), widget=TextInput(), required=False) 
    a_city = forms.CharField(label=_(u'City'), widget=TextInput(), required=False) 
    a_country = forms.CharField(label=_(u'Country'), widget=TextInput(), required=False) 

    # Override the save method like this 
    def save(self, commit=True): 
     c = super(CustomersForm, self).save(commit=False) 

     # Address 
     if c.address: 
      a = c.address 
     else: 
      a = Addresses() 
     a.street = self.cleaned_data.get('a_street') 
     a.city = self.cleaned_data.get('a_city') 
     a.postal_code = self.cleaned_data.get('a_postal_code') 
     a.country = self.cleaned_data.get('a_country') 

     if commit: 
      a.save() 
      c.address = a 
      c.save() 
     return c 
関連する問題