【问题标题】:Django - Render the <label> of a single form fieldDjango - 呈现单个表单字段的 <label>
【发布时间】:2011-09-06 17:27:43
【问题描述】:

我在表单上选择性地呈现字段。

class SomeForm(forms.Form):
    foo = forms.ChoiceField(label='Some Foo', ...)
    bar = forms.BooleanField(label='Some Bar', ...)
    ...

我有一个自定义标签,它基于其他一些逻辑,让我可以使用标签中的 FIELD 上下文变量遍历我需要的表单字段:

{% fieldsineed %}
  {% if FIELD.field.widget|klass == "CheckboxInput" %}
    <li>{{ FIELD }} {{ FIELD.field.label }}</li>
  {% else %}
    <li>{{ FIELD.label }}: {{ FIELD }}</li>
  {% endif %}
{% endfieldsineed %}

klass 是我从here 得到的过滤器,它返回过滤值的类名。)

很遗憾,FIELD.label 只是一个字符串。有没有一种简单的方法可以为给定的表单字段呈现 &lt;label&gt; 标记?

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    https://docs.djangoproject.com/en/dev/topics/forms/#s-looping-over-the-form-s-fields

    展示你可以做到的

    {{ FIELD.label_tag }}
    

    应该呈现类似的东西

    <label for="id_fieldName">Fieldlabel:</label>
    

    【讨论】:

    • 确实花了 20 分钟阅读文档并使用 dir() 挖掘 shell。很容易错过。 DBAD
    • 如何在没有: 的情况下获得它?编辑:对不起,阅读有帮助。表格label_suffix 将帮助您...
    • 非常感谢。我已经找了一天多了。你还知道如何访问label_tagid 属性吗?
    • @KareemJeiroudi on docs.djangoproject.com/en/dev/ref/forms/api/… label_tag 方法采用 attrs 字典。我认为这可能有效。我建议您将此作为一个单独的问题提出,以获得完整的答案。
    猜你喜欢
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 2022-10-19
    • 2011-12-30
    • 1970-01-01
    相关资源
    最近更新 更多