接上一章.
上一章中介绍了django中的视图,视图是用来展示内容的,但是上一章的例子中,视图是用python的函数代码实现的,视图函数返回什么,页面就显示什么,这样就不是很方便,因为如果想要良好的效果的话,还需要在python函数中返回css样式,丰富的html文档。
基于这种原因,诞生了模板,模板在这里是一套显示内容的框架,利用这个框架可以快速的生成页面。
- 在polls下建立templates文件夹,再到tmplates文件夹下建立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 %}
- 更新下index()视图。
from django.http import HttpResponse
from django.template import loader
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {
'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))
至此,访问http://127.0.0.1:8000/polls/ ,如果出现问题列表,说明前面的操作没有问题。