Nested django form for foreignkey model

Deadly 提交于 2020-07-09 05:27:21

问题


I have two models that look something like

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)

And I would like to generate a form that looks something like below, although I have no idea how to save the address from within a view without hard coding each individual fields from within a view.

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

The closest thing I have come up with is something like

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']  

Is there a known/best-practice way of accomplishing this?

来源:https://stackoverflow.com/questions/49233050/nested-django-form-for-foreignkey-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!