Django 便捷函数 — Django 6.0.4 documentation(2026)
创始人
2026-06-02 15:22:25
0
Django教程

Django 便捷函数

django.shortcuts 收集助手函数和“跨”多级mvc的类,换句话说,为了方便起见,这些函数/类引入受控耦合。

render()

render(request, template_name, context=None, content_type=None, status=None, using=None)[source]

将给定的模板与给定的上下文字典组合在一起,并以渲染的文本返回一个 HttpResponse 对象。

Django does not provide a shortcut function which returns a TemplateResponse because the constructor of TemplateResponse offers the same level of convenience as render().

必选参数

request

用于生成此响应的请求对象。

template_name

要使用的模板的全名或模板名称的序列。如果给定一个序列,则将使用存在的第一个模板。有关如何查找模板的更多信息,请参见 模板加载文档

可选参数

context

要添加到模板上下文的值的字典。 默认情况下,这是一个空的字典。 如果字典中的值是可调用的,则视图将在渲染模板之前调用它。

content_type

用于结果文档的 MIME 类型。默认 'text/html'

status

响应的状态码默认为 200

using

用于加载模板的模板引擎的 NAME

例如

下面的示例使用 MIME 类型呈现模板 myapp/index.html application/xhtml+xml

from django.shortcuts import render


def my_view(request):
    # View code here...
    return render(
        request,
        "myapp/index.html",
        {
            "foo": "bar",
        },
        content_type="application/xhtml+xml",
    )

此示例相当于:

from django.http import HttpResponse
from django.template import loader


def my_view(request):
    # View code here...
    t = loader.get_template("myapp/index.html")
    c = {"foo": "bar"}
    return HttpResponse(t.render(c, request), content_type="application/xhtml+xml")

redirect()

redirect(to, *args, permanent=False, preserve_request=False, **kwargs)[source]

返回一个 HttpResponseRedirect,指向传递参数的适当 URL。

参数可以是:

  • A model: the model's get_absolute_url() function will be called.

  • 视图名,可能带有的参数:reverse() 将被用于反向解析名称。

  • 一个绝对或相对 URL,将按原样用作重定向位置。

By default, a temporary redirect is issued with a 302 status code. If permanent=True, a permanent redirect is issued with a 301 status code.

If preserve_request=True, the response instructs the user agent to preserve the method and body of the original request when issuing the redirect. In this case, temporary redirects use a 307 status code, and permanent redirects use a 308 status code. This is better illustrated in the following table:

permanent

preserve_request

HTTP status code

True

False

301

False

False

302

False

True

307

True

True

308

Changed in Django 5.2:

The argument preserve_request was added.

示例

你可以通过多种方法使用 redirect() 函数。

  1. 传递对象,对象的 get_absolute_url() 方法将被调用来指向重定向地址:

    from django.shortcuts import redirect
    
    
    def my_view(request):
        ...
        obj = MyModel.objects.get(...)
        return redirect(obj)
    
  2. 传递视图名和一些可选的位置或关键字参数;URL 将使用 reverse() 方法来反向解析:

    def my_view(request):
        ...
        return redirect("some-view-name", foo="bar")
    
  3. 通过传递一个硬编码的 URL 来进行重定向:

    def my_view(request):
        ...
        return redirect("/some/url/")
    

    这也适用于完整的 URL:

    def my_view(request):
        ...
        return redirect("https://example.com/")
    

默认情况下,redirect() 返回临时重定向。所有以上形式都接受 permanent 参数;如果设置为 True 会返回一个永久重定向:

def my_view(request):
    ...
    obj = MyModel.objects.get(...)
    return redirect(obj, permanent=True)

Additionally, the preserve_request argument can be used to preserve the original HTTP method:

def my_view(request):
    # ...
    obj = MyModel.objects.get(...)
    if request.method in ("POST", "PUT"):
        # Redirection preserves the original request method.
        return redirect(obj, preserve_request=True)
    # ...

resolve_url()

resolve_url(to, *args, **kwargs)[source]

Returns a URL string by resolving and normalizing the given to argument into a concrete URL. The parameter to may be:

  • An object implementing get_absolute_url(), in which case the method will be called and its result returned.

  • A view name, view function, or view class, possibly with arguments passed as *args and **kwargs, in which case reverse() will be used to reverse-resolve the view.

  • A URL string, which will be returned unchanged.

This function is used internally by the redirect() shortcut to determine the target URL for the redirect location.

示例

  1. Resolving a URL for a model that defines get_absolute_url():

    models.py
    from django.db import models
    from django.urls import reverse
    
    
    class Article(models.Model):
        title = models.CharField(max_length=100)
    
        def get_absolute_url(self):
            return reverse("article-detail", args=[self.pk])
    
    views.py
    from django.http import JsonResponse
    from django.shortcuts import get_object_or_404, resolve_url
    from .models import Article
    
    
    def article_api_view(request, pk):
        """Return metadata about an article, including its canonical URL."""
        article = get_object_or_404(Article, pk=pk)
        return JsonResponse(
            {
                "id": article.pk,
                "title": article.title,
                "url": resolve_url(article),
            }
        )
    
  2. Resolving a target URL for use outside of a redirect, such as in an HTTP response header:

    from django.conf import settings
    from django.http import HttpResponse
    from django.shortcuts import resolve_url
    
    
    def login_success(request):
        response = HttpResponse("Login successful")
        response["X-Next-URL"] = resolve_url(settings.LOGIN_REDIRECT_URL)
        return response
    

get_object_or_404()

get_object_or_404(klass, *args, **kwargs)[source]
aget_object_or_404(klass, *args, **kwargs)

异步版本aget_object_or_404()

Calls get() on a given model manager, but it raises Http404 instead of the model's DoesNotExist exception.

参数

klass

从中获取对象的 Model 类, Manager ,或 QuerySet 实例。

*args

Q 对象.

**kwargs

查询参数,应采用 get()filter() 接受的格式。

例如

下面的例子是展示从 MyModel 中获取主键为1的对象:

from django.shortcuts import get_object_or_404


def my_view(request):
    obj = get_object_or_404(MyModel, pk=1)

此示例相当于:

from django.http import Http404


def my_view(request):
    try:
        obj = MyModel.objects.get(pk=1)
    except MyModel.DoesNotExist:
        raise Http404("No MyModel matches the given query.")

如上所示,最常用的使用案例是传递 Model 。但是,你也可以传递一个 QuerySet 实例:

queryset = Book.objects.filter(title__startswith="M")
get_object_or_404(queryset, pk=1)

以上例子有点冗长,因为它等同于:

get_object_or_404(Book, title__startswith="M", pk=1)

但如果你是从其他地方传递的 queryset 变量,那它会很有用。

最后,你也可以使用 Manager 。如果你有自定义管理器( custom manager )会很有用:

get_object_or_404(Book.dahl_objects, title="Matilda")

你也可以使用关联管理器( related managers ):

author = Author.objects.get(name="Roald Dahl")
get_object_or_404(author.book_set, title="Matilda")

注意:与 get() 一样,如果查询结果有多个对象,那么会引发 MultipleObjectsReturned 异常。

get_list_or_404()

get_list_or_404(klass, *args, **kwargs)[source]
aget_list_or_404(klass, *args, **kwargs)

异步版本aget_list_or_404()

Returns the result of filter() on a given model manager cast to a list, raising Http404 if the resulting list is empty.

参数

klass

从中获取列表的 ModelManagerQuerySet 实例。

*args

Q 对象.

**kwargs

查询参数,应采用 get()filter() 接受的格式。

例如

下面的例子展示从 MyModel 中获取所有 published=True 的对象:

from django.shortcuts import get_list_or_404


def my_view(request):
    my_objects = get_list_or_404(MyModel, published=True)

此示例相当于:

from django.http import Http404


def my_view(request):
    my_objects = list(MyModel.objects.filter(published=True))
    if not my_objects:
        raise Http404("No MyModel matches the given query.")

Last update:

4月 20, 2026


本文整理自 Django 6.0 官方中文文档,转载请注明出处。

相关内容

热门资讯

玻璃硬盘原理图 玻璃硬盘原理 玻璃硬盘,又称为磁头悬浮硬盘(Magnetic Head Flying Disk,MHFD),是一种...
闲鱼搜索规则与技巧 闲鱼最新特... 在闲鱼这个二手交易平台上,有很多用户都希望能够找到一些特殊的东西,比如一些罕见的收藏品、独特的手工艺...
家里监控最长能保存多少天的记录... 家里监控一般保存多久 随着科技的发展,家庭监控系统已经成为了许多家庭的必备设备,它不仅可以帮助我们...
华为tag有用吗 华为tag-... 华为Tag是华为手机中的一种功能,它可以帮助用户更好地管理自己的手机数据和应用,通过使用华为Tag,...
ps5手柄可用手机快充充电吗 ... PS5手柄,即PlayStation 5的DualSense手柄,是索尼公司为PlayStation...
QQ音乐提示代理模式可能无法正... QQ音乐提示代理模式可能无法正常访问,如上图所示,是怎么回事呢? 这个可能和你的网络设置有关系,首先...
收到微信有提示音怎么去掉 微信... 微信收到信息没有提示音,可能是由多种原因导致的,以下是一些可能的原因及解决方法: 1. 手机静音或...
a100显卡对应的cuda版本 在进行GPU加速的编程中,CUDA是常用的架构和平台,其版本和显卡型号之间存在着一定的对应关系。本篇...
别人打电话听不见我说话怎么回事... 当我们在使用手机时,可能会遇到别人打电话过来听不见声音的情况,这种情况可能是由多种原因导致的,下面我...
苹果手机非通讯录电话打不进来 ... 手机电话打不进来可能有多种原因,以下是一些常见的问题及解决方法: 1. **信号问题**: ...