WojtylaCz
WojtylaCz

Reputation: 368

How to differ formsets in django when using modelformset_factory?

Let's say I have an Contact object and I want to have two groups of contact Formsets in django(1.8) divided by fieldset tag in html template. I use modelformset_factory. Regardless I use one or two different factory functions, fields in these two formsets have same id in html. Since http.Request.body is dictionary, I lose information about one of the two formsets.

contacts_formset = modelformset_factory(
  models.Contact,
  form=forms.ContactDetailForm,
  extra=2)

contacts_escalation_formset_new = contacts_formset(
    queryset=models.Contact.objects.none())

contacts_other_formset_new = contacts_formset(
    queryset=models.Contact.objects.none())

in HTML:

input id="id_form-0-name" maxlength="155" name="form-0-name" type="text"
input id="id_form-0-name" maxlength="155" name="form-0-name" type="text"

For simple django form, there is keyword "prefix=..." . But this factory function does not have this argument. How can I solve it?

Upvotes: 2

Views: 1447

Answers (1)

Alasdair
Alasdair

Reputation: 308949

The modelformset_factory class returns a FormSet class. This FormSet class has a optional prefix argument, similar to Form classes.

contacts_escalation_formset_new = contacts_formset(
    prefix='escalation',
    queryset=models.Contact.objects.none(),
)

contacts_other_formset_new = contacts_formset(
    prefix='other'
    queryset=models.Contact.objects.none(),
)

See the docs on using more than one formset in a view for another example.

Upvotes: 4

Related Questions