Django 便捷函数

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

render()

render(request, template_name, context=None, content_type=None, status=None, using=None)[源代码]

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

Django没有提供返回 TemplateResponse 的便捷函数,因为 TemplateResponse 的构造函数提供了与 render() 同等程度的便利。

必选参数

request

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

template_name

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

可选参数

context

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

content_type

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

status

响应的状态码默认为 200

using

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

例如

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

  1. from django.shortcuts import render
  2. def my_view(request):
  3. # View code here...
  4. return render(
  5. request,
  6. "myapp/index.html",
  7. {
  8. "foo": "bar",
  9. },
  10. content_type="application/xhtml+xml",
  11. )

此示例相当于:

  1. from django.http import HttpResponse
  2. from django.template import loader
  3. def my_view(request):
  4. # View code here...
  5. t = loader.get_template("myapp/index.html")
  6. c = {"foo": "bar"}
  7. return HttpResponse(t.render(c, request), content_type="application/xhtml+xml")

redirect()

redirect(to, *args, permanent=False, **kwargs)[源代码]

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

参数可以是:

  • 一个模型:模型的 get_absolute_url() 函数将被调用。
  • 视图名,可能带有的参数:reverse() 将被用于反向解析名称。
  • 一个绝对或相对 URL,将按原样用作重定向位置。

默认情况下发出临时重定向;通过传递 permanent=True 发出永久重定向。

示例

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

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

    ``` from django.shortcuts import redirect

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

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

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

    这也适用于完整的 URL:

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

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

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

get_object_or_404()

get_object_or_404(klass, *args, **kwargs)[源代码]

aget_object_or_404(klass, *args, **kwargs)

异步版本aget_object_or_404()

在给定的模型管理器( model manager) 上调用 get() ,但它会引发 Http404 而不是模型的 DoesNotExist 异常。

参数

klass

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

*args

Q 对象.

**kwargs

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

例如

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

  1. from django.shortcuts import get_object_or_404
  2. def my_view(request):
  3. obj = get_object_or_404(MyModel, pk=1)

此示例相当于:

  1. from django.http import Http404
  2. def my_view(request):
  3. try:
  4. obj = MyModel.objects.get(pk=1)
  5. except MyModel.DoesNotExist:
  6. raise Http404("No MyModel matches the given query.")

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

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

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

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

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

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

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

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

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

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

Changed in Django 5.0:

aget_object_or_404() 函数已添加。

get_list_or_404()

get_list_or_404(klass, *args, **kwargs)[源代码]

aget_list_or_404(klass, *args, **kwargs)

异步版本aget_list_or_404()

返回给定模型管理器上 filter() 转换为列表的结果,如果结果列表为空,则引发 Http404

参数

klass

从中获取列表的 ModelManagerQuerySet 实例。

*args

Q 对象.

**kwargs

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

例如

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

  1. from django.shortcuts import get_list_or_404
  2. def my_view(request):
  3. my_objects = get_list_or_404(MyModel, published=True)

此示例相当于:

  1. from django.http import Http404
  2. def my_view(request):
  3. my_objects = list(MyModel.objects.filter(published=True))
  4. if not my_objects:
  5. raise Http404("No MyModel matches the given query.")

Changed in Django 5.0:

aget_list_or_404() 函数已添加。