2

I have many "polls" in my webapp, in which I have them all showing up on the same page, but cannot figure out how to have one submit(vote) button for all of the forms. As of right now, they all have their own vote buttons for each question, but I would like just one at the bottom to submit everything.

My HTML code for this template is as follows:

{% if latest_question_list %}
  {% for question in latest_question_list %}
  <h2>{{ question.question.text }}</h2>
  <form action="{% url 'polls:vote' question.id %}" method="post">
  {% csrf_token %}
  {% for choice in question.choice_set.all %}

      <input type="radio" name="choice" id="choice{{ for loop.counter }}" value="{{ choice.id }}" />
      <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />

   {% endfor %}

   <input type="radio" name="choice" value="">Other: <input type="text" />
   <br><input type="submit" value="Vote" /></br>
   </form>
   {% endfor %}

{% else %}
   <p>No polls are available.</p>
{% endif %}

Is there an easy way to do this? I appreciate any help! Thanks.

user2163296
  • 35
  • 2
  • 5

1 Answers1

2

See - django submit two different forms with one submit button

Django's form class, when supplied data from the request, looks at POST or GET to find values by element id. All fields within the form must have unique id's or use the Django form's prefix keyword when constructing the form in your view.

In short - put all your form elements within a single html tag, use the prefix keyword (with unique prefixes for each Django form, any time the form is constructed in the view; this will alter the input/select/radiobox elements' id attribute ), and go from there. Supply the GET or POST to each form instance and
your good to go.

However, your code above shows you manually populating the id of each field. Rather, why not pass each form to the template as include as {{ form_name.as_p }} ? Unless you have a good reason to do otherwise, you are probably creating a headache for yourself.

Community
  • 1
  • 1
Ian Price
  • 7,416
  • 2
  • 23
  • 34