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
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
Viewsubclass defines asynchronous (async def) method handlers,as_view()will mark the returned callable as a coroutine function. AnImproperlyConfiguredexception 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().Assigns the
HttpRequestto the view’srequestattribute, and any positional and/or keyword arguments captured from the URL pattern to theargsandkwargsattributes, respectively.If overriding this method, you must call
super().
- dispatch(request, *args, **kwargs)¶
The
viewpart of the view – the method that accepts arequestargument 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
GETwill be delegated toget(), aPOSTtopost(), and so on.By default, a
HEADrequest will be delegated toget(). If you need to handleHEADrequests in a different way thanGET, you can override thehead()method. See 다른 HTTP 메소드 지원 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
HttpResponseNotAllowedwith a list of allowed methods in plain text.
- options(request, *args, **kwargs)¶
Handles responding to requests for the OPTIONS HTTP verb. Returns a response with the
Allowheader 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 withawait.
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:
Method Flowchart
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) with the keyword arguments captured from the URL pattern that served the view.You can also add context using the
extra_contextkeyword argument foras_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 anHttpResponseGone(410).Ancestors (MRO)
This view inherits methods and attributes from the following view:
Method Flowchart
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
Noneto 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. IfFalse, then the redirect will use status code 302. By default,permanentisFalse.
- 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. IfFalse, then the query string is discarded. By default,query_stringisFalse.
Methods
- get_redirect_url(*args, **kwargs)¶
리다이렉션을 위한 타겟 URL을 생성합니다.
The
argsandkwargsarguments are positional and/or keyword arguments captured from the URL pattern, respectively.The default implementation uses
urlas a starting string and performs expansion of%named parameters in that string using the named groups captured in the URL.If
urlis not set,get_redirect_url()tries to reverse thepattern_nameusing what was captured in the URL (both named and unnamed groups are used).If requested by
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.