【问题标题】:'for' loop through form fields and excluding one of the fields with 'if''for' 循环遍历表单字段并排除带有 'if' 的字段之一
【发布时间】:2010-10-17 03:25:18
【问题描述】:

我遇到的问题如下:

我有:

{% for field in form %}
    {{ field }}
{% end for %}

我想要的是放置一个“if”语句来排除提供 .label 或任何内容的字段。喜欢:

{% for field in form%}
    {% if field == title %}
    {% else %}
        {{ field }}
    {% endif %}
{% endfor %}

有可能吗?我要很多字段一一写出来,只排除一两个。

感谢您的任何提示。

BR, Czlowiekwidmo。

【问题讨论】:

    标签: python django-templates


    【解决方案1】:

    是的,这应该是可能的:

    {% for field in form %}
        {% ifnotequal field.label title %}
            {{ field }}
        {% endifnotequal %}
    {% endfor %}
    

    Django 的 template tags 提供 ifequalifnotequal 变体,您可以针对上下文变量或字符串测试 field.label。

    【讨论】:

    • 没有被弃用,所以一个简单的 {% if field.name == 'title' %} 就可以了。比较标签也很糟糕,因为它可能会在翻译中发生变化。
    【解决方案2】:

    您可能会更乐意创建表单的子类,不包括违规字段。 见http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#form-inheritance

    class SmallerForm( MyForm ):
        class Meta(MyForm.Meta):
            exclude = [ title ]
    

    【讨论】:

    • +1。这是比 {% if %} 更好的解决方案。我也尝试在表单上使用 as_* 渲染方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多