Django 便捷函数Link to this heading

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

render()Link to this heading

render(request, template_name, context=None, content_type=None, status=None, using=None)Link to this definition

将给定的模板与给定的上下文字典组合在一起,并以渲染的文本返回一个 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().

必选参数Link to this heading

request

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

template_name

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

可选参数Link to this heading

context

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

content_type

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

status

响应的状态码默认为 200

using

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

例如Link to this heading

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

Code
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",
    )

此示例相当于:

Code
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()Link to this heading

redirect(to, *args, permanent=False, preserve_request=False, **kwargs)Link to this definition

返回一个 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

示例Link to this heading

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

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

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

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

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

    这也适用于完整的 URL:

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

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

Code
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:

Code
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()Link to this heading

resolve_url(to, *args, **kwargs)Link to this definition

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.

示例Link to this heading

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

    models.py
    Python
    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
    Python
    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:

    Code
    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()Link to this heading

get_object_or_404(klass, *args, **kwargs)Link to this definition
aget_object_or_404(klass, *args, **kwargs)Link to this definition

异步版本aget_object_or_404()

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

参数Link to this heading

klass

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

*args

Q 对象.

**kwargs

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

例如Link to this heading

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

Code
from django.shortcuts import get_object_or_404


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

此示例相当于:

Code
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 实例:

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

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

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

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

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

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

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

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

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

get_list_or_404()Link to this heading

get_list_or_404(klass, *args, **kwargs)Link to this definition
aget_list_or_404(klass, *args, **kwargs)Link to this definition

异步版本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.

参数Link to this heading

klass

从中获取列表的 ModelManagerQuerySet 实例。

*args

Q 对象.

**kwargs

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

例如Link to this heading

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

Code
from django.shortcuts import get_list_or_404


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

此示例相当于:

Code
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.")