0

I have form for adding Company:

class Company(models.Model):
name = models.CharField(max_length=50, )
profile = models.ForeignKey("Profile", blank=True, null=True)
sector = models.ForeignKey("Sector", blank=True, null=True)

I want to dynamically add another form on same site when proper button is clicked. For example after clicking "Add Address" button, form should be extended with:

city = models.ForeignKey("City", blank=True, null=True)
street_name = models.CharField(max_length=50, blank=True)

and submiting this form will create new Customer, Address and CustomerAddress records. I already have worked out solution which isn't perfect, cause I added "blank=True", to fields in additional forms and show/hide form in JS. This soultion is causing another problem, because now I don't have any validation for form.

I don't want to create custom validation for every template, in which I add multiple forms.

majercak
  • 3
  • 1
  • 3

1 Answers1

0

Have a different form for each model, instead of using one form.

When the user clicks the "Add address" button, add a hidden input to the tempalte.

<input type="hidden" name="add-address" />

Then in your view, only instantiate the address form when the hidden input is present.

if "add-address" in request.POST:
    address_form = AddressForm(request.POST)
else:
    address_form = AddressForm()

This way, you can make the fields in your address form required.

Alasdair
  • 298,606
  • 55
  • 578
  • 516