Django 便捷函数¶
包 django.shortcuts 收集助手函数和“跨”多级mvc的类,换句话说,为了方便起见,这些函数/类引入受控耦合。
render()¶
- render(request, template_name, context=None, content_type=None, status=None, using=None)[source]¶
- 将给定的模板与给定的上下文字典组合在一起,并以渲染的文本返回一个 - 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 :
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, **kwargs)[source]¶
- 返回一个 - HttpResponseRedirect,指向传递参数的适当 URL。- 参数可以是: - 一个模型:模型的 - get_absolute_url()函数将被调用。
- 视图名,可能带有的参数: - reverse()将被用于反向解析名称。
- 一个绝对或相对 URL,将按原样用作重定向位置。 
 - 默认情况下发出临时重定向;通过传递 - permanent=True发出永久重定向。
示例¶
你可以通过多种方法使用 redirect() 函数。
- 传递对象,对象的 - get_absolute_url()方法将被调用来指向重定向地址:- from django.shortcuts import redirect def my_view(request): ... obj = MyModel.objects.get(...) return redirect(obj) 
- 传递视图名和一些可选的位置或关键字参数;URL 将使用 - reverse()方法来反向解析:- def my_view(request): ... return redirect("some-view-name", foo="bar") 
- 通过传递一个硬编码的 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)
get_object_or_404()¶
- aget_object_or_404(klass, *args, **kwargs)¶
- 异步版本: - aget_object_or_404()- 在给定的模型管理器( model manager) 上调用 - get(),但它会引发- Http404而不是模型的- DoesNotExist异常。
参数¶
例如¶
下面的例子是展示从 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 异常。
aget_object_or_404() 函数已添加。
get_list_or_404()¶
- aget_list_or_404(klass, *args, **kwargs)¶
- 异步版本: - aget_list_or_404()
参数¶
例如¶
下面的例子展示从 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.")
aget_list_or_404() 函数已添加。
 
          