【问题标题】:Django: Grouping form fieldsDjango:对表单字段进行分组
【发布时间】:2021-08-31 02:29:13
【问题描述】:

我想对不同的表单域进行分组,如下例所示: forms.py

    a = SelectField()
    a.group = "Testgroup1"
    b = CheckboxField()
    b.group = "Testgroup1"
    c = IntegerField()
    c.group = "Testgroup2"
    d = IntegerField()
    d.group = "Testgroup2"
    e = CheckboxField()
    e.group = "Testgroup3"
    f = IntegerField()
    f.group = "Testgroup3"

然后在模板中是这样的:

{% for group in form %}
   {{ group }}
   {% for field in form %}
      <div> {{ field }} </div>
   {% endfor %}
{% endfor %}

我想要这样的结果: enter image description here

有人能给我一点建议吗? 提前谢谢你。

【问题讨论】:

    标签: html django


    【解决方案1】:

    这里有几个解决方案:

    最简单的做法是:

    <div id="group1">
      {{ form.a }}
      {{ form.b }}
    </div>
    <div id="group2">
      {{ form.c }}
      {{ form.d }}
    </div>
    

    如果您要处理很多字段,那么您可能希望在模板中进行过滤。这里有几个选项:

    令人讨厌的是,Django 在设计上不包含 filter 过滤器作为模板语言的一部分,但您可以按以下方式添加方法:

    How do I perform query filtering in django templates

    注意事项,Jinja is supported by Django out of the boxallows filtering like you would want

    请不要忘记您将按 field.field.group 进行排序。

    【讨论】:

    • 是的,我只是做了一个小例子。我认为这将是 20 个组和每组 10 个字段。
    • 更新了我的答案
    猜你喜欢
    • 2011-01-15
    • 2022-10-19
    • 1970-01-01
    • 2012-05-09
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    相关资源
    最近更新 更多