{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<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{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
#polls/urls.pyurl(r'^(?P<question_id>/d+)/vote/$', views.vote, name='vote'),#polls/views.pyfrom django.shortcuts import get_object_or_404, renderfrom django.http import HttPResponseRedirect, HttpResponsefrom django.core.urlresolvers import reversefrom polls.models import Choice, Question# ...def vote(request, question_id): p = get_object_or_404(Question, pk=question_id) try: selected_choice = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': p, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
# polls/view.py
from django.shortcuts import get_object_or_404, renderdef results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question})
from django.shortcuts import get_object_or_404, renderfrom django.http import HttpResponseRedirectfrom django.core.urlresolvers import reversefrom django.views import genericfrom polls.models import Choice, Questionclass IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5]class DetailView(generic.DetailView): model = Question#template_name 告诉django自动生成的template的name#如果不指定默认为<app name>/<model name>_detail.html template_name = 'polls/detail.html'#polls/urls.py#注意必须用<pk>指定匹配的组名urlpatterns = patterns('', url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>/d+)/$', views.DetailView.as_view(), name='detail'), )
#polls/templates/polls/index.html{% load staticfiles %}<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
新闻热点
疑难解答