Class-based views

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.

기본 예제

Django provides base view classes which will suit a wide range of applications. All views inherit from the View class, which handles linking the view into the URLs, HTTP method dispatching and other common features. RedirectView provides a HTTP redirect, and TemplateView extends the base class to make it also render a template.

Usage in your URLconf

The most direct way to use generic views is to create them directly in your URLconf. If you’re only changing a few attributes on a class-based view, you can pass them into the as_view() method call itself:

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

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

 as_view() 에 전달한 인자는 클래스의 속성(attributes)을 오버라이드(override)합니다. 이 예제에서는 TemplateView``에 ``template_name 을 설정합니다. 마찬가지로 url 속성(attirubte) 오버랑이딩 패턴을 :class:`~django.views.generic.base.RedirectView`에도 사용 할 수 있습니다.

제너릭 뷰의 상속(subclassing)

The second, more powerful way to use generic views is to inherit from an existing view and override attributes (such as the template_name) or methods (such as get_context_data) in your subclass to provide new values or methods. Consider, for example, a view that just displays one template, about.html. Django has a generic view to do this - TemplateView - so we can subclass it, and override the template name:

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

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

Then we need to add this new view into our URLconf. TemplateView is a class, not a function, so we point the URL to the as_view() class method instead, which provides a function-like entry to class-based views:

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

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

내장 제너릭 뷰의 사용법에 대한 자세한 내용은, 다음 토픽 :doc:`generic class-based views</topics/class-based-views/generic-display>`를 참조하세요.

다른 HTTP 메소드 지원

누군가 뷰를 API로 사용하여 HTTP를 통해 도서 라이브러리에 접근을 시도할 경우를 생각해 봅시다. API 클라이언트는 매 순간 접속하여 지난 방문 이후 새롭게 발행된 서적에 대한 도서 데이터를 다운로드 할 것 입니다. 하지만 그 이후로 새로운 도서가 나타나지 않으면, 데이터베이스에서 서적을 가져와 응답을 전체를 렌더링하여 클라이언트에게 보내는 것은 CPU의 시간과 대역폭을 낭비하는 것입니다. 이 경우, API에게 최근의 업데이트 도서에 대해 묻는것이 보다 나은 방법입니다.

URLconf 에서 URL을 book list 뷰와 매핑합니다:

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

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

그리고 뷰에서는:

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

New in Django 4.1.

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 비동기 지원.

Back to Top