【问题标题】:How to differ formsets in django when using modelformset_factory?使用modelformset_factory时如何在django中区分formset?
【发布时间】:2016-08-23 14:46:20
【问题描述】:

假设我有一个联系人对象,我想在 django(1.8) 中有两组联系人表单集,除以 html 模板中的 fieldset 标记。我使用modelformset_factory。无论我使用一个或两个不同的工厂函数,这两个表单集中的字段在 html 中具有相同的 id。由于 http.Request.body 是字典,因此我丢失了有关两个表单集之一的信息。

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

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

对于简单的 django 形式,有关键字 "prefix=..." 。但是这个工厂函数没有这个参数。我该如何解决?

【问题讨论】:

    标签: python django django-forms django-templates django-views


    【解决方案1】:

    modelformset_factory 类返回一个 FormSet 类。这个 FormSet 类有一个可选的 prefix 参数,类似于 Form 类。

    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(),
    )
    

    有关另一个示例,请参阅 using more than one formset in a view 上的文档。

    【讨论】:

    • 这很快。这是正确的。我刚刚点击了同一个 django 页面。
    猜你喜欢
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 2018-12-14
    • 2017-06-30
    • 2018-09-13
    • 1970-01-01
    相关资源
    最近更新 更多