【问题标题】:Get the ID of a field widget in a formset获取表单集中字段小部件的 ID
【发布时间】:2011-05-30 01:32:21
【问题描述】:

我想自定义表单集中表单的布局(即我不想使用 .as_table() 或 .as_p() 等)。我正在尝试获取表单字段的名称以在其标签的for 属性中使用,但我不知道该怎么做。我希望我不需要从头开始为该字段构建一个新的名称/ID。这是我现在正在使用的示例:

{% for form in formset.forms %}
<!-- The field for the "path" form field -->
<label for="{{what do I put here?}}">{{form.fields.path.label}}:</label><input type="text" id="{{django creates this one; do I have to do my own with the for loop counter or something?}}" name="{{probably the same as id}}" />
{% endfor %}

有没有“为表单集字段创建 ID”之类的方法?

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    这可能是你想要的。

    for="{{ form.your_field.html_name }}"
    

    【讨论】:

      【解决方案2】:

      首先,您要使用表单元素的id,而不是name

      我尝试了 Django 1.3 Alpha-1 并且以下工作:

      {% for form in formset.forms %}
          <label for="{{ form.my_field.auto_id }}">{{ form.my_field.label }}</label>
          {{ form.my_field }}
      {% endfor %}
      

      享受吧!

      【讨论】:

      • 声称这是一个无效的名称(Django 1.3 alpha 1)。另外,那不会输出
      • 我没有尝试过 Django 1.3 alpha 1,是的,它会输出一个标签标签,然后你可以用
        包围它。这也可以让你控制风格,但我承认这是一种解决方法。我很想知道这是否在 Django 1.3 alpha 1 中改变了行为。如果我发现其他任何东西,我一定会在这里分享 :)
      猜你喜欢
      • 2011-09-22
      • 2013-04-03
      • 2012-08-16
      • 2015-10-06
      • 1970-01-01
      • 2011-04-15
      • 2010-11-27
      • 1970-01-01
      • 2017-07-06
      相关资源
      最近更新 更多