---
title: "Django 便捷函数"
version: 5.2
locale: zh-hans
source: https://docs.djangoproject.com/zh-hans/5.2/topics/http/shortcuts/
canonical: https://djangodocs.dev/zh-hans/5.2/topics/http/shortcuts/
---
# Django 便捷函数

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

## `render()`

#### `render(request, template_name, context=None, content_type=None, status=None, using=None)`

将给定的模板与给定的上下文字典组合在一起，并以渲染的文本返回一个 [`HttpResponse`](/zh-hans/5.2/ref/request-response/#django.http.HttpResponse) 对象。

Django没有提供返回 [`TemplateResponse`](/zh-hans/5.2/ref/template-response/#django.template.response.TemplateResponse) 的便捷函数，因为 [`TemplateResponse`](/zh-hans/5.2/ref/template-response/#django.template.response.TemplateResponse) 的构造函数提供了与 [`render()`](#django.shortcuts.render) 同等程度的便利。

### 必选参数

**`request`**

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

**`template_name`**

  要使用的模板的全名或模板名称的序列。如果给定一个序列，则将使用存在的第一个模板。有关如何查找模板的更多信息，请参见 [模板加载文档](/zh-hans/5.2/topics/templates/#template-loading) 。

### 可选参数

**`context`**

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

**`content_type`**

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

**`status`**

  响应的状态码默认为 `200`。

**`using`**

  用于加载模板的模板引擎的 [`NAME`](/zh-hans/5.2/ref/settings/#std-setting-TEMPLATES-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)`

返回一个 [`HttpResponseRedirect`](/zh-hans/5.2/ref/request-response/#django.http.HttpResponseRedirect)，指向传递参数的适当 URL。

参数可以是：

- 一个模型：模型的 [`get_absolute_url()`](/zh-hans/5.2/ref/models/instances/#django.db.models.Model.get_absolute_url) 函数将被调用。
- 视图名，可能带有的参数：[`reverse()`](/zh-hans/5.2/ref/urlresolvers/#django.urls.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()`](#django.shortcuts.redirect) 函数。

1. 传递对象，对象的 [`get_absolute_url()`](/zh-hans/5.2/ref/models/instances/#django.db.models.Model.get_absolute_url) 方法将被调用来指向重定向地址：

   ```
   from django.shortcuts import redirect

   def my_view(request):
       ...
       obj = MyModel.objects.get(...)
       return redirect(obj)
   ```
2. 传递视图名和一些可选的位置或关键字参数；URL 将使用 [`reverse()`](/zh-hans/5.2/ref/urlresolvers/#django.urls.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()`](#django.shortcuts.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)
    # ...
```

## `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()`](/zh-hans/5.2/ref/models/querysets/#django.db.models.query.QuerySet.get) ，但它会引发 [`Http404`](/zh-hans/5.2/topics/http/views/#django.http.Http404) 而不是模型的 [`DoesNotExist`](/zh-hans/5.2/ref/models/class/#django.db.models.Model.DoesNotExist) 异常。

### 参数

**`klass`**

  从中获取对象的 [`Model`](/zh-hans/5.2/ref/models/instances/#django.db.models.Model) 类， [`Manager`](/zh-hans/5.2/topics/db/managers/#django.db.models.Manager) ，或  [`QuerySet`](/zh-hans/5.2/ref/models/querysets/#django.db.models.query.QuerySet) 实例。

**`*args`**

  [`Q 对象`](/zh-hans/5.2/ref/models/querysets/#django.db.models.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`](/zh-hans/5.2/ref/models/instances/#django.db.models.Model) 。但是，你也可以传递一个 [`QuerySet`](/zh-hans/5.2/ref/models/querysets/#django.db.models.query.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`](/zh-hans/5.2/topics/db/managers/#django.db.models.Manager) 。如果你有自定义管理器( [custom manager](/zh-hans/5.2/topics/db/managers/#custom-managers) )会很有用：

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

你也可以使用关联管理器( [`related managers`](/zh-hans/5.2/ref/models/relations/#django.db.models.fields.related.RelatedManager) )：

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

注意：与 `get()` 一样，如果查询结果有多个对象，那么会引发 [`MultipleObjectsReturned`](/zh-hans/5.2/ref/exceptions/#django.core.exceptions.MultipleObjectsReturned) 异常。

## `get_list_or_404()`

#### `get_list_or_404(klass, *args, **kwargs)`

#### `aget_list_or_404(klass, *args, **kwargs)`

*异步版本*：`aget_list_or_404()`

返回给定模型管理器上 [`filter()`](/zh-hans/5.2/ref/models/querysets/#django.db.models.query.QuerySet.filter) 转换为列表的结果，如果结果列表为空，则引发 [`Http404`](/zh-hans/5.2/topics/http/views/#django.http.Http404)。

### 参数

**`klass`**

  从中获取列表的 [`Model`](/zh-hans/5.2/ref/models/instances/#django.db.models.Model) ，[`Manager`](/zh-hans/5.2/topics/db/managers/#django.db.models.Manager) 或 [`QuerySet`](/zh-hans/5.2/ref/models/querysets/#django.db.models.query.QuerySet) 实例。

**`*args`**

  [`Q 对象`](/zh-hans/5.2/ref/models/querysets/#django.db.models.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.")
```
