2

My form is

class AnswerForm(ModelForm):
    class Meta:
      model=Answers
      fields=['answer']
      widgets ={'answer': TinyMCE(attrs={'cols': 80, 'rows': 30},  mce_attrs={'mode':"textareas",}),}

and in my view I am creating an instance of the form answerForm=AnswerForm(). In the template I have many instances of the answerForm inside a for loop

<form action="/q/answer/" method="post" style="display:none;" class="answer_form" >
{% csrf_token %}
{# {{ context.answerForm.as_p }} #}
{# <textarea id="{{ forloop.counter }}">{{ context.answerForm.answer }}</textarea> #}
{{ context.answerForm.answer }}

<input type="hidden" name="q_id_a" id="q_id_a" value="{{ result.object.id }}">
<input type="submit" value="Submit" />

my question:

  • how to instantiate django form in the view to create a unique HTML id for the field answer. Similar question was asked here the suggestion was to use auto_id. ContactForm(auto_id='id_for_%s') as mentioned in the django form documents modifies the id name format for all the form fields, but still I could not understand how to make django form field unique for multiple instances.
  • I am facing problems because of nonunique html id that the form is generating.
4

1 回答 1

4

如果您在页面上有多个表单实例,则应该使用表单集,它会为您创建唯一的 ID 和字段名称。

于 2016-05-19T14:44:25.653 回答