---
title: "Base views"
version: 6.1
locale: ko
source: https://docs.djangoproject.com/ko/6.1/ref/class-based-views/base/
canonical: https://djangodocs.dev/ko/6.1/ref/class-based-views/base/
---
# Base views

다음 세 가지 클래스는 Django 뷰를 만드는 데 필요한 많은 기능을 제공합니다. 사용자가 직접 사용하거나 상속할 수 있는 *parent* 뷰로 생각할 수 있습니다. 프로젝트에 필요한 모든 기능을 제공하지 못할 수 있습니다. 이 경우 Mixins 및 Generic class-based view가 있습니다.

Django의 기본 제공 클래스 기반 뷰 중 많은 것이 다른 클래스 기반 뷰 또는 다양한 믹스인에서 상속됩니다. 이 상속 체인은 매우 중요하기 때문에 상위 클래스는 **Ancestors (MRO)** 섹션 제목으로 문서화되어 있습니다. MRO는 Method Resolution Order의 약자입니다.

## `View`

#### `class django.views.generic.base.View`

기본 뷰 클래스입니다. 다른 모든 클래스 기반 뷰는 이 기본 클래스에서 상속됩니다. 그것은 엄밀히 말하면 일반적인 견해가 아니기 때문에 django.views\`\`에서 가져올 수도 있습니다.

**Method Flowchart**

1. [`setup()`](#django.views.generic.base.View.setup)
2. [`dispatch()`](#django.views.generic.base.View.dispatch)
3. [`http_method_not_allowed()`](#django.views.generic.base.View.http_method_not_allowed)
4. [`options()`](#django.views.generic.base.View.options)

**Example views.py**:

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

class MyView(View):
    def get(self, request, *args, **kwargs):
        return HttpResponse("Hello, World!")
```

**Example urls.py**:

```
from django.urls import path

from myapp.views import MyView

urlpatterns = [
    path("mine/", MyView.as_view(), name="my-view"),
]
```

**Attributes**

#### `http_method_names`

이 뷰에서 허용할 HTTP 메서드 이름 목록입니다.

기본:

```
["get", "post", "put", "patch", "delete", "head", "options", "trace"]
```

**Methods**

#### `classmethod as_view(**initkwargs)`

요청을 받고 응답을 반환하는 호출 가능 보기를 반환합니다:

```
response = MyView.as_view()(request)
```

반환된 뷰는 `view_class` 및 `view_initkwargs` 속성을 가지고 있습니다.

요청/응답 주기 동안 뷰가 호출되면 ```setup`메소드는 뷰의 "request" 속성에  :class:`~django.http.HttpRequest`를 할당하고 모든 위치 및/또는 키워드 argument :ref:`captured from the URL pattern <how-django-processes-a-request>를 각각 ``args`()``` 및 `kwargs` 속성에 할당합니다. 그러면 :meth:dispatch\`가 호출됩니다.

If a `View` subclass defines asynchronous (`async def`) method
handlers, `as_view()` will mark the returned callable as a coroutine
function. An `ImproperlyConfigured` exception will be raised if both
asynchronous (`async def`) and synchronous (`def`) handlers are
defined on a single view-class.

#### `setup(request, *args, **kwargs)`

Performs key view initialization prior to [`dispatch()`](#django.views.generic.base.View.dispatch).

Assigns the [`HttpRequest`](/ko/6.1/ref/request-response/#django.http.HttpRequest) to the view’s `request`
attribute, and any positional and/or keyword arguments
[captured from the URL pattern](/ko/6.1/topics/http/urls/#how-django-processes-a-request)
to the `args` and `kwargs` attributes, respectively.

If overriding this method, you must call `super()`.

#### `dispatch(request, *args, **kwargs)`

The `view` part of the view – the method that accepts a `request`
argument plus arguments, and returns an HTTP response.

The default implementation will inspect the HTTP method and attempt to
delegate to a method that matches the HTTP method; a `GET` will be
delegated to `get()`, a `POST` to `post()`, and so on.

By default, a `HEAD` request will be delegated to `get()`. If you
need to handle `HEAD` requests in a different way than `GET`, you
can override the `head()` method. See
[다른 HTTP 메소드 지원](/ko/6.1/topics/class-based-views/#supporting-other-http-methods) for an example.

#### `http_method_not_allowed(request, *args, **kwargs)`

If the view was called with an HTTP method it doesn’t support, this
method is called instead.

The default implementation returns `HttpResponseNotAllowed` with the
list of allowed methods in the `Allow` header, as required by
[**RFC 7231**](https://datatracker.ietf.org/doc/html/rfc7231.html#section-6.5.5). The response body is empty.

#### `options(request, *args, **kwargs)`

Handles responding to requests for the OPTIONS HTTP verb. Returns a
response with the `Allow` header containing a list of the view’s
allowed HTTP method names.

If the other HTTP methods handlers on the class are asynchronous
(`async def`) then the response will be wrapped in a coroutine
function for use with `await`.

## `TemplateView`

#### `class django.views.generic.base.TemplateView`

Renders a given template, with the context containing parameters captured
in the URL.

**Ancestors (MRO)**

This view inherits methods and attributes from the following views:

- [`django.views.generic.base.TemplateResponseMixin`](/ko/6.1/ref/class-based-views/mixins-simple/#django.views.generic.base.TemplateResponseMixin)
- [`django.views.generic.base.ContextMixin`](/ko/6.1/ref/class-based-views/mixins-simple/#django.views.generic.base.ContextMixin)
- [`django.views.generic.base.View`](#django.views.generic.base.View)

**Method Flowchart**

1. [`setup()`](#django.views.generic.base.View.setup)
2. [`dispatch()`](#django.views.generic.base.View.dispatch)
3. [`http_method_not_allowed()`](#django.views.generic.base.View.http_method_not_allowed)
4. [`get_context_data()`](/ko/6.1/ref/class-based-views/mixins-simple/#django.views.generic.base.ContextMixin.get_context_data)

**Example views.py**:

```
from django.views.generic.base import TemplateView

from articles.models import Article

class HomePageView(TemplateView):
    template_name = "home.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["latest_articles"] = Article.objects.all()[:5]
        return context
```

**Example urls.py**:

```
from django.urls import path

from myapp.views import HomePageView

urlpatterns = [
    path("", HomePageView.as_view(), name="home"),
]
```

**Context**

- Populated (through [`ContextMixin`](/ko/6.1/ref/class-based-views/mixins-simple/#django.views.generic.base.ContextMixin)) with
  the keyword arguments captured from the URL pattern that served the view.
- You can also add context using the
  [`extra_context`](/ko/6.1/ref/class-based-views/mixins-simple/#django.views.generic.base.ContextMixin.extra_context) keyword
  argument for [`as_view()`](#django.views.generic.base.View.as_view).

## `RedirectView`

#### `class django.views.generic.base.RedirectView`

Redirects to a given URL.

The given URL may contain dictionary-style string formatting, which will be
interpolated against the parameters captured in the URL. Because keyword
interpolation is *always* done (even if no arguments are passed in), any
`"%"` characters in the URL must be written as `"%%"` so that Python
will convert them to a single percent sign on output.

If the given URL is `None`, Django will return an `HttpResponseGone`
(410).

**Ancestors (MRO)**

This view inherits methods and attributes from the following view:

- [`django.views.generic.base.View`](#django.views.generic.base.View)

**Method Flowchart**

1. [`setup()`](#django.views.generic.base.View.setup)
2. [`dispatch()`](#django.views.generic.base.View.dispatch)
3. [`http_method_not_allowed()`](#django.views.generic.base.View.http_method_not_allowed)
4. [`get_redirect_url()`](#django.views.generic.base.RedirectView.get_redirect_url)

**Example views.py**:

```
from django.shortcuts import get_object_or_404
from django.views.generic.base import RedirectView

from articles.models import Article

class ArticleCounterRedirectView(RedirectView):
    permanent = False
    query_string = True
    pattern_name = "article-detail"

    def get_redirect_url(self, *args, **kwargs):
        article = get_object_or_404(Article, pk=kwargs["pk"])
        article.update_counter()
        return super().get_redirect_url(*args, **kwargs)
```

**Example urls.py**:

```
from django.urls import path
from django.views.generic.base import RedirectView

from article.views import ArticleCounterRedirectView, ArticleDetailView

urlpatterns = [
    path(
        "counter/<int:pk>/",
        ArticleCounterRedirectView.as_view(),
        name="article-counter",
    ),
    path("details/<int:pk>/", ArticleDetailView.as_view(), name="article-detail"),
    path(
        "go-to-django/",
        RedirectView.as_view(url="https://www.djangoproject.com/"),
        name="go-to-django",
    ),
]
```

**Attributes**

#### `url`

The URL to redirect to, as a string. Or `None` to raise a 410 (Gone)
HTTP error.

#### `pattern_name`

The name of the URL pattern to redirect to. Reversing will be done
using the same args and kwargs as are passed in for this view.

#### `permanent`

Whether the redirect should be permanent. The only difference here is
the HTTP status code returned. If `True`, then the redirect will use
status code 301. If `False`, then the redirect will use status code
\302. By default, `permanent` is `False`.

#### `query_string`

Whether to pass along the GET query string to the new location. If
`True`, then the query string is appended to the URL. If `False`,
then the query string is discarded. By default, `query_string` is
`False`.

#### `preserve_request`

> **New in Django 6.1**

Whether to preserve the HTTP method and body during the redirect. If
`True`, then the redirect will use status code 307 instead of 302,
or 308 instead of 301 when [`permanent`](#django.views.generic.base.RedirectView.permanent) is `True`. By default,
`preserve_request` is `False`.

**Methods**

#### `get_redirect_url(*args, **kwargs)`

리다이렉션을 위한 타겟 URL을 생성합니다.

The `args` and `kwargs` arguments are positional and/or keyword
arguments [captured from the URL pattern](/ko/6.1/topics/http/urls/#how-django-processes-a-request), respectively.

The default implementation uses [`url`](#django.views.generic.base.RedirectView.url) as a starting
string and performs expansion of `%` named parameters in that string
using the named groups captured in the URL.

If [`url`](#django.views.generic.base.RedirectView.url) is not set, `get_redirect_url()` tries to reverse the
[`pattern_name`](#django.views.generic.base.RedirectView.pattern_name) using what was captured in the URL (both named and
unnamed groups are used).

If requested by [`query_string`](#django.views.generic.base.RedirectView.query_string), it will also append the query
string to the generated URL.
Subclasses may implement any behavior they wish, as long as the method
returns a redirect-ready URL string.
