第一个django应用:第三部分

60 阅读1分钟

本文主要讲述 django 路由相关的操作

添加视图

image.png

模版页面

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

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))

快捷函数:render()

相对于上一种写法的简写,不用导入 loader 和 HttpResponse

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)

抛出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})

快捷函数:get_object_or_404()

from django.shortcuts import get_object_or_404, 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})

模版系统

查看 模板指南 可以了解关于模板的更多信息。

去除模板中的硬编码 URL

由于在 polls.urls 模块中的 path() 函数中定义了 name 参数,可以通过使用 {% url %} 模板标签来消除对 url 配置中定义的特定 URL 路径的依赖

image.png

# before
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>

# after
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>

为 URL 名称添加命名空间

区分不同 app 的同名 url

image.png