R / Richie全部文章 ↑

Python · 2 分钟阅读

视图高级特性与快捷方法

掌握反向解析、重定向、render 三大件,效率翻倍。

1. URL 反向解析

不要在代码里硬编码 URL,而是给 path 命名后用 reverse 解析。

# urls.py
path("dymmmic/<int:year>/<mth:month>/<int:day>/", views.dynamic_hello, name="dynamic_hello")
# views.py
from django.urls import reverse
from django.http import HttpResponseRedirect

def go(request):
    url = reverse("post:dynamic_hello", args=[2026, 1, 15])
    return HttpResponseRedirect(url)

命名空间

# config/urls.py
path("post/", include("post.urls", namespace="bbs_post"))

# post/urls.py
app_name = "post"

模板里:

{% url 'post:dynamic_hello' 2026 1 15 %}

2. 重定向

方式 状态码 适用
HttpResponseRedirect 302 临时跳转(默认)
HttpResponsePermanentRedirect 301 永久跳转(SEO)

redirect() 快捷方式支持:

from django.shortcuts import redirect

# 1. 传 URL 名称
redirect("post:topic_detail", pk=1)

# 2. 传绝对/相对 URL
redirect("/post/topic/1/")
redirect("./list/")

# 3. 传带 get_absolute_url 的对象
redirect(topic)

permanent=True 即 301。

3. 常用快捷方法

render

from django.shortcuts import render

return render(request, "post/topic_list.html", context, status=200)

推荐在视图中默认使用 render,它会创建 RequestContext,从而启用 user、perms、messages 等模板变量。

render_to_response

不再推荐使用,因为它不会自动注入 RequestContext。

get_object_or_404

from django.shortcuts import get_object_or_404

topic = get_object_or_404(Topic, pk=1)

可传 Model / Manager / QuerySet,匹配多条仍会抛 MultipleObjectsReturned。

get_list_or_404

from django.shortcuts import get_list_or_404

topics = get_list_or_404(Topic, is_online=True)

这两个方法 4.0+ 引入了新版,能更好地与异步视图协作。

4. 会话与消息

# 写
request.session["fav_color"] = "blue"
messages.success(request, "保存成功")

# 读(仅视图)
fav = request.session.get("fav_color")

模板里通过 {{ messages }} 渲染,前提是 MIDDLEWARE 含 MessageMiddleware 且模板用了 django.contrib.messages 上下文处理器。