如何为嵌套模型构建表单?

时间:2016-09-21 13:27:19

标签: django-models django-forms django-1.9

我正在使用模型Customers和Addresses:

在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)

我是Django的新手,如果错误太多,请原谅我。

我想使用表单创建一个新客户:

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'}))

但我仍然希望能够添加地址。我读了一些关于嵌套表格的内容,但我不明白。

请帮助您构建一个表单,创建一个名称,电子邮件,电话号码和地址的客户?

1 个答案:

答案 0 :(得分: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