【问题标题】:Creating Form element ids in the form template in Django在 Django 的表单模板中创建表单元素 ID
【发布时间】:2012-02-09 22:26:01
【问题描述】:

我是 Django 新手,我正在尝试创建一个包含下拉列表的表单。这是为了在单击提交时根据用户在这些下拉列表中的选择生成脚本。

问题是以下表单模板正在创建重复的表单元素 id

即使要重复下拉菜单,如何在表单模板中创建唯一 ID。

以下是下拉菜单的代码。

<html>
<table border="1">
  <form action="/PrintTestScript/" method="post">
  {% csrf_token %}
  <tr>
    <th>Action</th>
    <th>Endpoint</th>
    <th>Status</th>
    <th>Box Type</th>
  </tr>
  {% for i in 0123456789|make_list %}
  <tr>
    <td>
       {{form.action}}
    </td>
    <td>
       {{form.series}}
    </td>
    <td>
       {{form.epstatus}}
    </td>
    <td>
       {{form.boxtype}}
  </tr>
  {% endfor %}
  <tr>
    <td>
      <input type="submit" value="Submit" />
    </td>
  </tr>
 </form>
 </table>
 </html>

以下是表单类定义。

  class TestForm(ModelForm):
      action = forms.ModelChoiceField(queryset=actions.objects.all(), empty_label="")
      series = forms.ModelChoiceField(queryset=endpoints.objects.all(), empty_label="")
      epstatus = forms.ModelChoiceField(queryset=status.objects.all(), empty_label="")
      boxtype = forms.ModelChoiceField(queryset=boxtype.objects.all())

      class Meta:
          model = endpoints
          exclude = ('end_point_alias', 'dial_num', 'ip_address')

这是创建视图的地方

def getvals(request):
      form = TestForm()

      return render_to_response('main.html', {'form':form}, context_instance=RequestContext(request))

感谢您的帮助。

【问题讨论】:

    标签: django django-models django-forms django-templates django-views


    【解决方案1】:

    您需要将&lt;form&gt; 标记放在for 循环中,这样您实际上创建了10 个不同的表单,而不是相同表单元素的10 个副本。但是您仍然需要 10 个单独的提交按钮。如果您实际上是在寻找表单列表,请查看 Django FormSet documentation.

    【讨论】:

    • 感谢 FormSet 的输入。我不愿意进入 formset.. 但现在我看到它非常强大。感谢您的投入。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 2012-08-21
    • 2017-10-05
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 2014-02-28
    相关资源
    最近更新 更多