简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM