20121023 django学习笔记4

在模板中创建表单

 1 <h1>{{ poll.question }}</h1>
 2 
 3 {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
 4 
 5 <form action="/polls/{{ poll.id }}/vote/" method="post">
 6 {% csrf_token %}
 7 {% for choice in poll.choice_set.all %}
 8     <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
 9     <label for="choice{{ forloop.counter }}">{{ choice.choice }}</label><br />
10 {% endfor %}
11 <input type="submit" value="Vote" />
12 </form>

对应表单的回调页面

 1 from django.template import RequestContext
 2 from polls.models import Poll, Choice
 3 from django.http import HttpResponse, HttpResponseRedirect
 4 from django.shortcuts import render_to_response, get_object_or_404
 5 from django.core.urlresolvers import reverse
 6 
 7 def index(request):
 8     latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
 9     return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
10 
11 def detail(request, poll_id):
12     p = get_object_or_404(Poll, pk=poll_id)
13     return render_to_response('polls/detail.html', {'poll': p}, context_instance=RequestContext(request))
14 
15 def results(request, poll_id):
16     p = get_object_or_404(Poll, pk=poll_id)
17     return render_to_response('polls/results.html', {'poll': p})
18 
19 def vote(request, poll_id):
20     p = get_object_or_404(Poll, pk=poll_id)
21     try:
22         selected_choice = p.choice_set.get(pk=request.POST['choice'])
23     except (KeyError, Choice.DoesNotExist):
24         return render_to_response('polls/detail.html', {
25             'poll': p,
26             'error_message': "You didn't select a choice.",
27         }, context_instance=RequestContext(request))
28     else:
29         selected_choice.votes += 1
30         selected_choice.save()
31         return HttpResponseRedirect(reverse('polls.views.results', args=(p.id,)))
posted @ 2012-10-23 15:59  zhu327  阅读(226)  评论(0)    收藏  举报