【问题标题】:Django: loop a call to a template+viewDjango:循环调用模板+视图
【发布时间】:2011-04-19 01:09:04
【问题描述】:

我正在进行多页投票。我有一个数据库,它有一个名为 page 的列,每页有 4 个问题。用户回答完一个页面上的所有问题后,点击“Next”进入下一页。

我可以查询数据库以确定我需要生成的页面数,但我不确定如何循环模板呈现过程。

这是我的代码:

用户输入:

def index(request):
latest_poll_list = Poll.objects.filter(page=1)
t = loader.get_template('index.html')
c = Context({
    'latest_poll_list': latest_poll_list,
})
return HttpResponse(t.render(c))

...生成此模板:

    <ul>

<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="{{poll.id}}choice{{ forloop.counter }}" value="{{ choice.id }}" />
            <label for="choice{{ forloop.counter }}">{{ choice.choice }}</label><br />
        {% endfor %}
{% endfor %}
    <input type="submit" value="Vote" />
</form>

</ul>

...然后在这里处理用户的选择:

def vote(request):
intra_page_key = request.POST['choice1']+','+request.POST['choice2']+','+request.POST['choice3']
request.session['p1'] = intra_page_key
return HttpResponse(request.session['p1'])

如何在投票的第 2 页重复此顺序?

【问题讨论】:

    标签: django templates loops


    【解决方案1】:

    你可能想看看FormWizard

    【讨论】:

      【解决方案2】:
      #urls.py
      (r'^(?P<pollid>\d*)/$', 'app.views.index'),
      
      #views.py
      def index(request, pollid):    
          latest_poll_list = Poll.objects.filter(page=pollid)
          t = loader.get_template('index.html')
          c = Context({
              'latest_poll_list': latest_poll_list,
          })
          return HttpResponse(t.render(c))
      

      最好阅读一下快捷方式“get or 404”

      http://docs.djangoproject.com/en/dev/intro/tutorial03/?from=olddocs#a-shortcut-get-object-or-404

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-07-25
        • 2014-08-18
        • 2021-12-26
        • 2013-08-31
        • 2021-07-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多