开发者

Capture the results of multiple radiobox selection Django

开发者 https://www.devze.com 2023-02-26 08:26 出处:网络
Total newb here... I\'m making a poll where I display 5 questions on a page.Each question has 4 radioboxes.

Total newb here...

I'm making a poll where I display 5 questions on a page. Each question has 4 radioboxes.

In my django template, I'm looping through a container (latest_poll_list) of all my questions (poll):

    <form action="/first/vote/" method="post">
{% csrf_token %}
{% for poll in latest_poll_list %}
    <li>{{ poll.question }}</li>
        {% for choice in poll.choice_set.all %}
            <input type="radio" name="choice{{poll.id}}" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
            <label for="choice{{ forloop.counter }}">{{ choice.choice }}</label><br />
        {% endfor %}
{% endfor %}
    <input type="submit" value="Vote" />
</form>

Lastly h开发者_如何学Pythonow do I return results from multiple questions? Do I have to put the choice+poll.id into an array/container?

Also, how does django know that forloop.counter refers to the inner loop and not the outer loop? Thanks for your patience while I ramp up!


I would consider using a formset or a model formset.

and the forloop.counter is for the inner most forloop, however you can pass the counter from an outer forloop into the inner forloop using the {% with %} tag:

{% for object in objects %}
    <label>{{ forloop.counter }}</label>
    {% with outside_counter=forloop.counter %}
    {% for subobject in object %}               
    <p>outside: {{ outside_counter }} inside: {{ forloop.counter }}</p>
    {% endfor %}
    {% endwith %}
{% endfor %}

results:

<label>0</label>
<p>outside: 0 inside: 0</p>
<p>outside: 0 inside: 1</p>
<label>1</label>
<p>outside: 1 inside: 0</p>
<p>outside: 1 inside: 1</p>
...
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号