编写拥有实际功能的视图
每个视图函数只负责处理两件事中的一件: 返回一个包含所请求页面内容的 HttpResponse对象,
或抛出一个诸如Http404异常.该如何去做这两件事,就看你自己的想法了。
Django 只要求返回的是一个HttpResponse,或者抛出一个异常。
因为方便,让我们使用教程1中介绍的Django自己的数据库API。下面是一个新的index()视图,
它显示系统中最新发布的5条questions记录
这里有一个问题,页面的设计被硬编码在视图中。 如果你想改变页面的外观,就得编辑这段Python代码。
因此,让我们使用Django的模板系统,通过创建一个视图能够调用的模板,将页面的设计从Python中分离出来。
首先,在你的polls目录下创建一个叫做templates的目录,Django将在这里查找模板
你项目的TEMPLATES设置描述了Django将如何加载并渲染模板,默认的设置文件
settings.py配置了一个DjangoTemplates后端,其中将APP_DIR选项设置为True.
按照惯例,DjangoTemplates在 INSTALLED_APPS所包含的每个应用的目录下查找名为"templates"子目录。因此即使我们不像教程 2.中那样去修改DIRS,Django也可以找到应用的模版。
组织模板
我们可以将我们所需要的模板聚在一起,放在一个大的模板目录下,且可以运行地很好。
然而,我们这个模板属于投票应用,不像我们在先前教程中创建的管理站点模板
在你刚刚创建的templates目录中,创建另外一个目录polls,并在其中创建一个文件index.html
换句话讲,你的模板应该位于 polls/templates/polls/index.html。
模板命名空间:
现在,我们可以直接将我们放在polls/templates(而不用创建另外一个polls子目录),但实际上这是个坏主意
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 %}
现在让我们更新polls/views.py 中的index视图来使用模板:
polls/views.py
from django.http import HttpResponse
from django.template import RequestContext, loader
from .models import Question
node2:/exam/mysite/polls#cat views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from .models import Question
from django.template import RequestContext, loader
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')
template = loader.get_template('polls/index.html')
context ={'latest_question_list':latest_question_list}
return HttpResponse(template.render(context))
def detail(request, question_id):
return HttpResponse(" call detail 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)