【问题标题】:Access a subset of django form fields访问 django 表单字段的子集
【发布时间】:2019-03-10 05:20:54
【问题描述】:

如何在 django 的表单字段子集之间插入标记,同时保持 DRY?

给定:

class CompensationUpdate(UpdateView):
    model = Compensation
    fields = [
        'salary1',
        'salary2',
        'incentive1',
        'incentive2', ]

我希望能够在视图中访问它们,以便我可以将它们的组包装在标记中。例如:

<div class="ibox-content">
    {% for field in form.salary_fields %}
        ...
    {% endfor %}
</div>
<div class="ibox-content">
    {% for field in form.incentive_fields %}
        ...
    {% endfor %}
</div>

我在大约 10 个组中的表单上有超过 50 个字段,因此我需要以 DRY 方式执行此操作。虽然我可以单独访问每个字段,但我不知道如何定义子集(在 UpdateView 中或直接在模板中)。

【问题讨论】:

    标签: django django-forms django-views


    【解决方案1】:

    您可以使用django-betterforms,其中有FieldSets,您可以将字段分组。

    在表单的 Meta 类中,指定分组字段的 FieldSet:

    class Meta:
        fieldsets = (
            ('info', {'fields': ('username', 'email')}),
            ('location', {'fields': ('address', ('city', 'state', 'zip'))}),
            ('password', {'password1', 'password2'}),
        )
    

    在模板中,您可以遍历 FieldSets

    {% for fieldset in form %}
        <div class="ibox-content">
            {% for field in fieldset %}
                ...
            {% endfor %}
        </div>
    {% endfor %}
    

    你可以看到更多proposed template implementation here

    其他解决方案是this answerdjango-form-utils,这是我的答案的更好记录版本。然而,后者今天似乎没有维护,但可以根据您的 Django 版本工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 2018-11-05
      • 2012-06-06
      • 2021-09-05
      • 2013-08-24
      • 2012-06-04
      • 1970-01-01
      相关资源
      最近更新 更多