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.
Community
  • 1
  • 1
Javed
  • 5,904
  • 4
  • 46
  • 71

1 Answers1

4

If you have multiple instances of a form on a page, you should be using a formset, which will take care of creating unique IDs and field names for you.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895