上次的是简单的返回一段文字这次具体的创建实现视图,因为在视图里,不会因为没有一个界面都会创建一个视图,而是创建几个公共视图让大家一起用,可以说是模版。
所以先创建公共视图
在我们的投票应用中,我们需要下列几个视图:
- 问题索引页——展示最近的几个投票问题。
- 问题详情页——展示某个投票的问题和不带结果的选项列表。
- 问题结果页——展示某个投票的结果。
- 投票处理器——用于响应用户为某个问题的特定选项投票的操作。
在 Django 中,网页和其他内容都是从视图派生而来。每一个视图表现为一个简单的 Python 函数(或者说方法,如果是在基于类的视图里的话)。Django 将会根据用户请求的 URL 来选择使用哪个视图,具体可以看我们之后的view文件
编写更多视图
mysite/polls/views.py
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
output = ', '.join([q.question_text for q in latest_question_list])
return HttpResponse(output)
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
如果只是这样只是实现了视图,没有办法让浏览器访问,需要在路由系统里添加每个视图对应的函数和相关网址格式,所以要在urls文件里添加
mysite/polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
# ex: /polls/
path('', views.index, name='index'),
# ex: /polls/5/
path('specifics/<int:question_id>/', views.detail, name='detail'),
# ex: /polls/5/results/
path('<int:question_id>/results/', views.results, name='results'),
# ex: /polls/5/vote/
path('<int:question_id>/vote/', views.vote, name='vote'),
]
这里如果输入网址为/polls/34/vote/
会调用path(‘int:question_id/vote/’, views.vote, name=‘vote’),对应的question_id的值为34
具体的页面是不会写在具体的函数里,所以一般是写成模版
在你的 polls 目录里创建一个 templates 目录。Django 将会在这个目录里查找模板文件。在你刚刚创建的 templates 目录里,再创建一个目录 polls,然后在其中新建一个文件 index.html 。
polls/templates/polls/index.html
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
更新一下 mysite/polls/views.py 里的 index 视图来使用模板:
from django.http import HttpResponse
from django.shortcuts import render
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_data')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
render函数作用是载入模板,填充上下文,再返回由它生成的 HttpResponse 对象
这里的context中’latest_question_list’: latest_question_list,是为了传入html 文件里的latest_question_list({% for question in latest_question_list %})
抛出 404 错误
当我们指定问题 ID 所对应的问题不存在,这个视图就会抛出一个 Http404 异常。
mysite/polls/views.py
from django.http import Http404
from django.shortcuts import render
from .models import Question
# ...
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
mysite/polls/templates/polls/detail.html
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
去除模板中的硬编码 URL
在mysite/polls/index.html中有硬编码
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
硬编码和强耦合的链接,对于一个包含很多应用的项目来说,修改起来是十分困难的。然而,因为你在 polls.urls 的 url() 函数中通过 name 参数为 URL 定义了名字,你可以使用 {% url %} 标签代替它:
修改为
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
编写一个简单的表单
更新一下投票详细页面的模板
mysite/polls/templates/polls/detail.html
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url '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>
- 上面的模板在 Question 的每个 Choice 前添加一个单选按钮。 每个单选按钮的 value 属性是对应的各个 Choice 的 ID。每个单选按钮的 name 是 “choice” 。这意味着,当有人选择一个单选按钮并提交表单提交时,它将发送一个 POST 数据 choice=# ,其中# 为选择的 Choice 的 ID。
- 我们设置表单的 action 为 {% url ‘polls:vote’ question.id %} ,并设置 method=“post” 。
forloop.counter 指示 for 标签已经循环多少次。 - 所有针对内部 URL 的 POST 表单都应该使用 {% csrf_token %} 模板标签,防止跨站点请求伪造。
上面的提交按钮是提交到polls:vote上,所以要对vote函数进行相应的修改
mysite/polls/views.py
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'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('results', args=(question.id,)))
-
request.POST[‘choice’] 以字符串形式返回选择的 Choice 的 ID
-
如果在 request.POST[‘choice’] 数据中没有提供 choice , POST 将引发一个 KeyError 。上面的代码检查 KeyError ,如果没有给出 choice 将重新显示 Question 表单和一个错误信息。直接传到detail.html文件中,输出error_message
-
在增加 Choice 的得票数之后,代码返回一个 HttpResponseRedirect 而不是常用的 HttpResponse 、 HttpResponseRedirect 只接收一个参数:用户将要被重定向的 URL,在成功处理post数据之后,应该始终返回HttpResponseRedirect。
-
我们在 HttpResponseRedirect 的构造函数中使用 reverse() 函数。这个函数避免了我们在视图函数中硬编码 URL。它需要我们给出我们想要跳转的视图的名字和该视图所对应的 URL 模式中需要给该视图提供的参数。 在本例中,reverse() 调用将返回一个这样的字符串:’/polls/3/results/’
reverse(‘polls:results’, args=(question.id,))
重定向到结果界面,我们要获得相应的参数即question_id,修改
mysite/polls/views.py
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})
同时创建results.html 模版
mysite/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 'detail' question.id %}">Vote again?</a>