---
title: "Tampilan berdasarkan-kelas"
version: 6.0
locale: id
source: https://docs.djangoproject.com/id/6.0/topics/class-based-views/
canonical: https://djangodocs.dev/id/6.0/topics/class-based-views/
---
# Tampilan berdasarkan-kelas

A view is a callable which takes a request and returns a
response. This can be more than just a function, and Django provides
an example of some classes which can be used as views. These allow you
to structure your views and reuse code by harnessing inheritance and
mixins. There are also some generic views for tasks which we'll get to later,
but you may want to design your own structure of reusable views which suits
your use case. For full details, see the [class-based views reference
documentation](/id/6.0/ref/class-based-views/).

- [Perkenalan ke tampilan berdasarkan-kelas](/id/6.0/topics/class-based-views/intro/)
- [Tampilan umum berdasarkan kelas siap-pakai](/id/6.0/topics/class-based-views/generic-display/)
- [Menangani formulir dengan tampilan berdasarkan-kelas](/id/6.0/topics/class-based-views/generic-editing/)
- [Menggunakan mixin dengan tampilan berdasarkan-kelas](/id/6.0/topics/class-based-views/mixins/)

## Contoh dasar

Django provides base view classes which will suit a wide range of applications.
All views inherit from the [`View`](/id/6.0/ref/class-based-views/base/#django.views.generic.base.View) class,
which handles linking the view into the URLs, HTTP method dispatching and other
common features. [`RedirectView`](/id/6.0/ref/class-based-views/base/#django.views.generic.base.RedirectView) provides a
HTTP redirect, and [`TemplateView`](/id/6.0/ref/class-based-views/base/#django.views.generic.base.TemplateView) extends the
base class to make it also render a template.

## Penggunaan dalam URLconf anda

Cara paling langsung untuk menggunakan tampilan umum adalah membuatnya langsung di URLconf anda. Jika anda hanya mengubah beberapa atribut pada tampilan berbasis kelas, anda dapat meneruskannya ke dalam pemanggilan metode [`as_view()`](/id/6.0/ref/class-based-views/base/#django.views.generic.base.View.as_view) itu sendiri:

```
from django.urls import path
from django.views.generic import TemplateView

urlpatterns = [
    path("about/", TemplateView.as_view(template_name="about.html")),
]
```

Apapun argumen dilewatkan ke [`as_view()`](/id/6.0/ref/class-based-views/base/#django.views.generic.base.View.as_view) akan menimpa atribut disetel pada kelas. Dalam contoh ini, kami menyetel template\_name\` pada `TemplateView`. Pola penibanan mirip dapat digunakan untuk atribut `url` pada [`RedirectView`](/id/6.0/ref/class-based-views/base/#django.views.generic.base.RedirectView).

## Mensubkelaskan tampilan umum

Cara kedua yang lebih ampuh untuk menggunakan tampilan umum adalah mewarisi dari tampilan yang ada dan mengganti atribut (seperti `template_name`) atau metode (seperti `get_context_data`) di subkelas anda untuk memberikan nilai atau metode baru . Perhatikan, misalnya, tampilan yang hanya menampilkan satu template, `about.html`. Django memiliki tampilan umum untuk melakukan ini - [`TemplateView`](/id/6.0/ref/class-based-views/base/#django.views.generic.base.TemplateView) \- jadi kita dapat mensubklasifikasikannya, dan mengganti nama cetakan:

```
# some_app/views.py
from django.views.generic import TemplateView

class AboutView(TemplateView):
    template_name = "about.html"
```

Kemudian kita perlu menambahkan tampilan baru ini ke dalam URLconf kita. `TemplateView` adalah kelas, bukan fungsi, jadi kami mengarahkan URL ke metode kelas [`as_view()`](/id/6.0/ref/class-based-views/base/#django.views.generic.base.View.as_view) , yang menyediakan masukan mirip fungsi ke tampilan berdasarkan kelas

```
# urls.py
from django.urls import path
from some_app.views import AboutView

urlpatterns = [
    path("about/", AboutView.as_view()),
]
```

Untuk informasi lebih pada bagaimana menggunakan tampilan umum siap pakai, obrolkan topik selanjutnya di [generic class-based views](/id/6.0/topics/class-based-views/generic-display/).

### mendukung cara HTTP lain

Misalkan seseorang ingin mengakses pustaka buku kami terhadap HTTP menggunakan tampilan sebagai sebuah klien API akan terhubung setiap sekarang kemudian dan mengunduh buku untuk buku diterbitkan sejak kunjugan terakhir. Tetapi jika tidak ada buku baru muncul sejak itu, itu adalah pembuangan dari waktu CPU dan lebar pita untuk mengambil buku-buku dari basisdata, mengirim tanggapan penuh dan mengirim itu ke klien. Itu mungkin lebih baik untuk menanyakan API ketika kebanyakan buku saat ini telah diterbitkan.

Kami memetakan UTL pada tampilan daftar buku di URLconf:

```
from django.urls import path
from books.views import BookListView

urlpatterns = [
    path("books/", BookListView.as_view()),
]
```

Dan tampilan:

```
from django.http import HttpResponse
from django.views.generic import ListView
from books.models import Book

class BookListView(ListView):
    model = Book

    def head(self, *args, **kwargs):
        last_book = self.get_queryset().latest("publication_date")
        response = HttpResponse(
            # RFC 1123 date format.
            headers={
                "Last-Modified": last_book.publication_date.strftime(
                    "%a, %d %b %Y %H:%M:%S GMT"
                )
            },
        )
        return response
```

If the view is accessed from a `GET` request, an object list is returned in
the response (using the `book_list.html` template). But if the client issues
a `HEAD` request, the response has an empty body and the `Last-Modified`
header indicates when the most recent book was published. Based on this
information, the client may or may not download the full object list.

## Asynchronous class-based views

As well as the synchronous (`def`) method handlers already shown, `View`
subclasses may define asynchronous (`async def`) method handlers to leverage
asynchronous code using `await`:

```
import asyncio
from django.http import HttpResponse
from django.views import View

class AsyncView(View):
    async def get(self, request, *args, **kwargs):
        # Perform io-blocking view logic using await, sleep for example.
        await asyncio.sleep(1)
        return HttpResponse("Hello async world!")
```

Within a single view-class, all user-defined method handlers must be either
synchronous, using `def`, or all asynchronous, using `async def`. An
`ImproperlyConfigured` exception will be raised in `as_view()` if `def`
and `async def` declarations are mixed.

Django will automatically detect asynchronous views and run them in an
asynchronous context. You can read more about Django's asynchronous support,
and how to best use async views, in [Dukungan asinkronus](/id/6.0/topics/async/).
