【问题标题】:Django boundfields auto naming: changing the form partDjango boundfields 自动命名:更改表单部分
【发布时间】:2021-12-08 07:44:11
【问题描述】:

我似乎无法找到这是否/如何可能。但是假设我有一个表格:

class Detform(ModelForm):

    class Meta:
        model = Ap_detcmd
        fields = ["foo"]


Formset = inlineformset_factory(ParentModel, ChildModel,
                                       form=Detform,
                                       can_delete=False,
                                       extra=0)

然后在模板中渲染,例如在管理表单(或任何字段)中:

<input type="hidden" name="ap_detcmd-TOTAL_FORMS" value="0" id="id_ap_detcmd-TOTAL_FORMS">

由于表单的模型是“Ap_detcmd”,所以我得到#id_ap_detcmd-....作为所有字段的前缀。

有没有办法指定该前缀?

【问题讨论】:

    标签: django forms


    【解决方案1】:

    好的,简而言之:

    • 子类 BaseInlineFormset
    • 将 {"prefix":"foo"} 添加到 init 中的 kwargs 并将其传递给
    • 魔法

    例如:

    class MyBaseInlineFormset(BaseInlineFormSet):
        def __init__(self, *args, **kwargs):
            kwargs["prefix"] = "foo"
            super().__init__(*args, **kwargs)
    

    那么你的 inlineformset 声明如下:

    DetPoFormset = inlineformset_factory(Ap_entcmd, Ap_detcmd, form=Detform, formset=MyBaseInlineFormset, can_delete=True, extra=0)
    

    那么你的管理表单输入(id_XXX-TOTAL_FORMS 等)会是这样的:

    <input type="hidden" name="foo-TOTAL_FORMS" value="0" id="id_foo-TOTAL_FORMS">
    

    以及表单集中的所有标签。

    【讨论】:

      猜你喜欢
      • 2020-05-13
      • 1970-01-01
      • 2013-11-01
      • 2013-11-26
      • 2012-02-28
      • 2017-06-06
      • 2016-03-26
      • 1970-01-01
      • 2022-07-14
      相关资源
      最近更新 更多