外键模型的嵌套django表单

时间:2018-03-12 10:32:45

标签: django django-models django-forms

我有两个类似

的模型
class Address(models.Model):
    line1 = models.CharField(max_length=128, help_text="Address Line 1")
    city = models.CharField(max_length=128)
    state = USStateField()
    zipcode = USZipCodeField()

class Company(models.Model):
    name = models.CharField(max_length=100)
    address = models.ForeignKey('Address', on_delete=models.PROTECT)

我想生成一个类似于下面的表单,虽然我不知道如何在视图中保存地址而不对视图中的每个字段进行硬编码。

<input type=text id="name">Name</input>
<input type=text id="line1">Address Line1</input>
<input type=text id="city">City</input>
<input type=text id="state">State</input>
<input type=text id="zipcode">Zipcode</input>

我提出的最接近的事情就像是

class CustomForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(CustomForm, self).__init__(*args, **kwargs)
        address_fields = forms.fields_for_model(Address, exclude=())
        self.fields.update(address_fields)

    class Meta:
        model = Company
        exclude = ['address']  

是否有已知/最佳实践方法来实现这一目标?

0 个答案:

没有答案