1)投票form
A.polls/templates/polls/detail.html:
<h1>{{ question.question_text }}</h1>
{% 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>
①<form action="表单提交的地址" method="表单提交的方法" >
②input标签:输入框,其中可以根据type的属性值改变输入框的作用。
<input type=“submit”/> 用户点击之后会自动提交 form
<input type=“radio”/> 单选框
③当需要创建一个改变服务器端数据的form时,用 method=”post”
④针对内部网址的所有POST表单都要用{% csrf_token %}
⑤forloop.counter:for循环循环次数
2)vote()函数实现
在polls/views.py加:
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from .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,)))
①request.POST[‘choice’] 以字符串形式返回选择的Choice的ID
②增加Choice票数之后,代码返回HttpResponseRedirect,③HttpResponseRedirect只接收一个参数:用户要被重定向的URL
HttpResponseRedirect的构造函数中使用reverse()函数,reverse()需要给出要跳转的视图的名称和该视图所对应的URL模式中需要给该视图提供的参数。
如:url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
上面url中需要的参数是question_id
在reverse中给出(reverse(‘polls:results’, args=(p.id,)))
④’/polls/3/results/’通过results函数将视图渲染为投票结果页面
poll/views:
from django.shortcuts import get_object_or_404, render
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
⑤polls/templates/polls/results.html:
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>
<a href="{% url 'polls:detail' question.id %}">Vote again?</a>
投票结果入下图所示:
3)使用generic views
转换为通过视图,要完成以下三步:
A.转换URLconf
B.删除不再需要的代码
C.引进基于Django通用视图的新视图
①polls/urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
在第二个和第三个正则表达式,模式匹配由 变成 主键
②修改polls/views.py为:
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from .models import Choice, Question
class 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 = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request, question_id):
... # same as above
③上面3个class继承于2个generic view:ListView 和 DetailView
④
⑤