【问题标题】:Capture the results of multiple radiobox selection Django捕获多个单选框选择Django的结果
【发布时间】:2011-04-17 01:09:02
【问题描述】:

这里的总新手...

我正在进行一项民意调查,我在一个页面上显示 5 个问题。每个问题都有 4 个单选框。

在我的 django 模板中,我正在循环一个包含所有问题(投票)的容器(latest_poll_list):

    <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>

最后,我如何返回多个问题的结果?我是否必须将choice+poll.id 放入数组/容器中?

另外,django 怎么知道 forloop.counter 指的是内循环而不是外循环? 感谢您在我升级时的耐心等待!

【问题讨论】:

    标签: django forms


    【解决方案1】:

    我会考虑使用formsetmodel formset

    forloop.counter 用于最内部的 forloop,但是您可以使用 {% with %} 标签将计数器从外部 forloop 传递到内部 forloop:

    {% 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 %}
    

    结果:

    <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>
    ...
    

    【讨论】:

      猜你喜欢
      • 2021-06-08
      • 1970-01-01
      • 2014-07-07
      • 1970-01-01
      • 2011-02-13
      • 2012-07-30
      • 2017-09-11
      • 2016-03-22
      • 1970-01-01
      相关资源
      最近更新 更多