---
title: "TemplateResponse dan``SimpleTemplateResponse``"
version: 5.1
locale: id
source: https://docs.djangoproject.com/id/5.1/ref/template-response/
canonical: https://djangodocs.dev/id/5.1/ref/template-response/
---
# `TemplateResponse` dan\`\`SimpleTemplateResponse\`\`

Standard [`HttpResponse`](/id/5.1/ref/request-response/#django.http.HttpResponse) objects are static structures.
They are provided with a block of pre-rendered content at time of
construction, and while that content can be modified, it isn't in a form that
makes it easy to perform modifications.

However, it can sometimes be beneficial to allow decorators or
middleware to modify a response *after* it has been constructed by the
view. For example, you may want to change the template that is used,
or put additional data into the context.

TemplateResponse provides a way to do just that. Unlike basic
[`HttpResponse`](/id/5.1/ref/request-response/#django.http.HttpResponse) objects, TemplateResponse objects retain
the details of the template and context that was provided by the view to
compute the response. The final output of the response is not computed until
it is needed, later in the response process.

## Obyek `SimpleTemplateResponse`

#### `class SimpleTemplateResponse`

### Atribut

#### `SimpleTemplateResponse.template_name`

Nama dari cetakan untuk dibangun. Menerima obyek cetakan tergantung-backend (seperti itu dikembalikan oleh [`get_template()`](/id/5.1/topics/templates/#django.template.loader.get_template)), nama dari cetakan, atau daftar dari nama-nama cetakan.

Contoh: `['foo.html', 'path/to/bar.html']`

#### `SimpleTemplateResponse.context_data`

Data konteks untuk digunakan ketika membangun cetakan. Itu harus berupa [`dict`](https://docs.python.org/3/library/stdtypes.html#dict).

Contoh: `{'foo': 123}`

#### `SimpleTemplateResponse.rendered_content`

Nilai dibangun saat ini dari isi tanggapan, menggunakan cetakan saat ini dan data konteks.

#### `SimpleTemplateResponse.is_rendered`

Sebuah boolean menunjukkan apakah tanggapan isi dapat dibangun.

### Cara

#### `SimpleTemplateResponse.__init__(template, context=None, content_type=None, status=None, charset=None, using=None, headers=None)`

Memberi contoh obyek [`SimpleTemplateResponse`](#django.template.response.SimpleTemplateResponse) dengan cetakan diberikan, konteks, jenis isi, keadaan HTTP, dan charset.

**`template`**

  Sebuah obyek cetakan bergantung-backend (seperti itu dikembalikan oleh [`get_template()`](/id/5.1/topics/templates/#django.template.loader.get_template)), nama dari cetakan, atau daftar dari nama-nama cetakan.

**`context`**

  Sebuah [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) dari nilai-nilai untuk menambahkan konteks cetakan. Secara awalan, ini adalah dictionary kosong.

**`content_type`**

  The value included in the HTTP `Content-Type` header, including the
  MIME type specification and the character set encoding. If
  `content_type` is specified, then its value is used. Otherwise,
  `'text/html'` is used.

**`status`**

  Kode keadaan HTTP untuk tanggapan.

**`charset`**

  Charset dimana tanggapan akan disandikan. Jika tidak diberikan itu akan dikeluarkan dari `content_type`, dan jika itu tidak berhasil, pengaturan [`DEFAULT_CHARSET`](/id/5.1/ref/settings/#std-setting-DEFAULT_CHARSET) akan digunakan.

**`menggunakan`**

  [`NAME`](/id/5.1/ref/settings/#std-setting-TEMPLATES-NAME) dari mesin cetakan untuk digunakan untuk memuat cetakan.

**`headers`**

  A [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) of HTTP headers to add to the response.

#### `SimpleTemplateResponse.resolve_context(context)`

Preprocesses context data that will be used for rendering a template.
Accepts a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) of context data. By default, returns the same
[`dict`](https://docs.python.org/3/library/stdtypes.html#dict).

Timpa metode ini untuk menyesuaikan konteks.

#### `SimpleTemplateResponse.resolve_template(template)`

Menyelesaikan contoh cetakan untuk digunakan untuk membangun. Menerima obyek cetakan bergantung-backend (seperti itu dikembalikan oleh [`get_template()`](/id/5.1/topics/templates/#django.template.loader.get_template)), nama dari cetakan, atau daftar dari nama-nama cetakan.

Mengembalikan contoh obyek cetakan bergantung-backend untuk dikirim.

TImpa metode ini untuk menyesuaikan pemuatan cetakan.

#### `SimpleTemplateResponse.add_post_render_callback()`

Add a callback that will be invoked after rendering has taken
place. This hook can be used to defer certain processing
operations (such as caching) until after rendering has occurred.

Jika [`SimpleTemplateResponse`](#django.template.response.SimpleTemplateResponse) sudah dibangun, callback akan dipanggil segera.

Ketika dipanggil, callback akan melewatkan argumen tunggal -- instance [`SimpleTemplateResponse`](#django.template.response.SimpleTemplateResponse) terbangun.

If the callback returns a value that is not `None`, this will be
used as the response instead of the original response object (and
will be passed to the next post rendering callback etc.)

#### `SimpleTemplateResponse.render()`

Sets `response.content` to the result obtained by
[`SimpleTemplateResponse.rendered_content`](#django.template.response.SimpleTemplateResponse.rendered_content), runs all post-rendering
callbacks, and returns the resulting response object.

`render()` will only have an effect the first time it is called. On
subsequent calls, it will return the result obtained from the first call.

## Obyek `TemplateResponse`

#### `class TemplateResponse`

`TemplateResponse` is a subclass of
[`SimpleTemplateResponse`](#django.template.response.SimpleTemplateResponse) that knows about
the current [`HttpRequest`](/id/5.1/ref/request-response/#django.http.HttpRequest).

### Cara

#### `TemplateResponse.__init__(request, template, context=None, content_type=None, status=None, charset=None, using=None, headers=None)`

Instantiates a [`TemplateResponse`](#django.template.response.TemplateResponse) object
with the given request, template, context, content type, HTTP status, and
charset.

**`request`**

  Sebuah instance [`HttpRequest`](/id/5.1/ref/request-response/#django.http.HttpRequest).

**`template`**

  Sebuah obyek cetakan bergantung-backend (seperti itu dikembalikan oleh [`get_template()`](/id/5.1/topics/templates/#django.template.loader.get_template)), nama dari cetakan, atau daftar dari nama-nama cetakan.

**`context`**

  Sebuah [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) dari nilai-nilai untuk menambahkan konteks cetakan. Secara awalan, ini adalah dictionary kosong.

**`content_type`**

  The value included in the HTTP `Content-Type` header, including the
  MIME type specification and the character set encoding. If
  `content_type` is specified, then its value is used. Otherwise,
  `'text/html'` is used.

**`status`**

  Kode keadaan HTTP untuk tanggapan.

**`charset`**

  Charset dimana tanggapan akan disandikan. Jika tidak diberikan itu akan dikeluarkan dari `content_type`, dan jika itu tidak berhasil, pengaturan [`DEFAULT_CHARSET`](/id/5.1/ref/settings/#std-setting-DEFAULT_CHARSET) akan digunakan.

**`menggunakan`**

  [`NAME`](/id/5.1/ref/settings/#std-setting-TEMPLATES-NAME) dari mesin cetakan untuk digunakan untuk memuat cetakan.

**`headers`**

  A [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) of HTTP headers to add to the response.

## Pengolahan membangun

Before a [`TemplateResponse`](#django.template.response.TemplateResponse) instance can be
returned to the client, it must be rendered. The rendering process takes the
intermediate representation of template and context, and turns it into the
final byte stream that can be served to the client.

Ada tiga keadaan dibawah mana `TemplateResponse` akan dibangun:

- Ketika contoh `TemplateResponse` secara tegas dibangun, menggunakan metode [`SimpleTemplateResponse.render()`](#django.template.response.SimpleTemplateResponse.render).
- Ketika isi dari tanggapan secara tegas disetel dengan memberikan `response.content`.
- Setelah melewatkan melalui cetakan tanggapan middleware, tetapi sebelum melewatkan melalui tanggapan middleware.

Sebuah `TemplateResponse` hanya dapat dibangun sekali. Panggilan pertama pada  [`SimpleTemplateResponse.render()`](#django.template.response.SimpleTemplateResponse.render) mensetel isi dari tanggapan; selanjutnya membangun panggilan untuk tidak merubah isi tanggapan.

However, when `response.content` is explicitly assigned, the
change is always applied. If you want to force the content to be
re-rendered, you can reevaluate the rendered content, and assign
the content of the response manually:

```pycon
# Set up a rendered TemplateResponse
>>> from django.template.response import TemplateResponse
>>> t = TemplateResponse(request, "original.html", {})
>>> t.render()
>>> print(t.content)
Original content

# Re-rendering doesn't change content
>>> t.template_name = "new.html"
>>> t.render()
>>> print(t.content)
Original content

# Assigning content does change, no render() call required
>>> t.content = t.rendered_content
>>> print(t.content)
New content
```

### Callback pasca-dibangun

Beberapa tindakan - seperti menyimpan sementara - tidak dapat dilakukan pada cetakan yang belum dibangun. Mereka harus dilakukan pada sepenuhnya lengkap dan tanggapan yang dibangun.

If you're using middleware, you can do that. Middleware provides
multiple opportunities to process a response on exit from a view. If
you put behavior in the response middleware, it's guaranteed to execute
after template rendering has taken place.

Bagaimanapun, jika anda sedang menggunakan penghias, kesempatan sama tidak ada. Perilaku apapun ditentukan dalam sebuah penghias ditangani segera.

Untuk mengimbangi ini (dan penggunaan kasus sejalan lainnya), [`TemplateResponse`](#django.template.response.TemplateResponse) mengizinkan anda mendaftarkan callback yang akan dipanggil ketika pembangunan lengkap. Menggunakan callback ini, anda dapat menunda pengolahan kritis sampai titik dimana anda dapat menjamin bahwa isi dibangun akan tersedia.

To define a post-render callback, define a function that takes
a single argument -- response -- and register that function with
the template response:

```
from django.template.response import TemplateResponse

def my_render_callback(response):
    # Do content-sensitive processing
    do_post_processing()

def my_view(request):
    # Create a response
    response = TemplateResponse(request, "mytemplate.html", {})
    # Register the callback
    response.add_post_render_callback(my_render_callback)
    # Return the response
    return response
```

`my_render_callback()` akan diminta setelah `mytemplate.html` telah dibangun, dan akan disediakan sepenuhnya contoh [`TemplateResponse`](#django.template.response.TemplateResponse) dibangun sebagai sebuah argumen.

Jika cetakan sudah dibangun, callback akan diminta segera.

## Menggunakan `TemplateResponse` dan `SimpleTemplateResponse`

A [`TemplateResponse`](#django.template.response.TemplateResponse) object can be used anywhere that a normal
[`django.http.HttpResponse`](/id/5.1/ref/request-response/#django.http.HttpResponse) can be used. It can also be used as an
alternative to calling [`render()`](/id/5.1/topics/http/shortcuts/#django.shortcuts.render).

For example, the following view returns a [`TemplateResponse`](#django.template.response.TemplateResponse) with a
template and a context containing a queryset:

```
from django.template.response import TemplateResponse

def blog_index(request):
    return TemplateResponse(
        request, "entry_list.html", {"entries": Entry.objects.all()}
    )
```
