Django中文官方版07-添加视图模板

1.添加模板文件

在与polls app目录下创建templates目录,再创建polls目录,为了区分模板目录中的多个app模板的其中一个,最后添加index.html,最终路径是polls/templates/polls/index.html

打开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 %}
注:有种jsp,markdown的既视感

2.修改视图文件,传统写法,使其支持模板方式

打开polls/views.py文件,修改成以下内容:

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))
注:注意内容中template关键词的地方哦

3.修改视图文件,捷径写法

打开polls/views.py文件,修改成以下内容:

from django.shortcuts import render

from .models import Question


def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)
4.加入404异常页面引用

打开polls/views.py文件,输入以下内容:

from django.http import Http404
from django.shortcuts import render

from .models import Question
# ...
def detail(request, question_id):
    try:
        question = Question.objects.get(pk=question_id)
    except Question.DoesNotExist:
        raise Http404("Question does not exist")
    return render(request, 'polls/detail.html', {'question': question})
注:注意看404关键词处

5.修改视图文件,方便测试上述404引用问题

打开polls/templates/polls/detail.html文件,修改内容为:

{{ question }}
6.启动runserver

python manage.py runserver

打开 http://127.0.0.1:8000/polls/ 点击


原文摘自官方地址https://docs.djangoproject.com/en/1.11/intro/tutorial03/,本文只做精简化翻译,详细内容可去指定地址阅读

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值