3

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?

  • have a look on "inline-formsets" in django – Shoaib Zafar Mar 12 '18 at 11:51
  • Do you know of a good example? The docs aren't very helpful and I'm having trouble finding a good example online. –  Mar 13 '18 at 09:53
  • I found [this answer](https://stackoverflow.com/a/1113086/9478968) but it looks like they are creating a form as part of a view. I'm not sure how to use this method as part of a class to be used in multiple views. –  Mar 13 '18 at 10:02
  • well, you can also check this example: https://medium.com/@adandan01/django-inline-formsets-example-mybook-420cc4b6225d . Hope you'll find it helpful. – Shoaib Zafar Mar 13 '18 at 10:46
  • Thank you for the example. Although, I'm not sure it is quite what I'm looking for in this situation. I would like to automatically generate the sub-form based on the `Address` model. The given example relies on [CreateView](https://docs.djangoproject.com/en/2.0/ref/class-based-views/generic-editing/#createview) which requires that the model fields are specified, thus not automatically generating the form. Also, that particular example got a little messy. The code is not clean and it seems it would be easier to manually create a form with the desired inputs. –  Mar 13 '18 at 11:41
  • I ended up using the solution you'd provided yourself – Sabrina Leggett Jun 09 '20 at 02:39

0 Answers0