Base viewsLink to this heading

以下の3つのクラスは、Django のビューの作成に必要な多くの機能を提供します。これらは Django ビューの 親の ビューと見なすことができ、それ自体で使うことも継承して使うこともできます。プロジェクトに必要な全ての機能を提供するわけではありませんが、その場合は Mixins と汎用クラスベースビューが使えます。

多くの Django のビルトインのクラスベースビューは、ほかのクラスベースビューや多種の mixin を継承しています。この継承チェーンは非常に重要なため、原型のクラスは 継承元 (MRO) セクションにドキュメントがあります。MRO は メソッド解決順序 (Method Resolution Order) の略です。

ViewLink to this heading

class django.views.generic.base.ViewLink to this definition

The base view class. All other class-based views inherit from this base class. It isn't strictly a generic view and thus can also be imported from django.views.

メソッドのフローチャート

  1. setup()

  2. dispatch()

  3. http_method_not_allowed()

  4. options()

Example views.py:

Code
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:

Code
from django.urls import path

from myapp.views import MyView

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

属性

http_method_namesLink to this definition

このビューが受け入れる HTTP メソッドの名称のリストです。

デフォルト値:

Code
['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

メソッド

classmethod as_view(**initkwargs)Link to this definition

リクエストを受け取ってレスポンスを返す、呼び出し可能なビューを返します:

Code
response = MyView.as_view()(request)

返されたビューは、view_classview_initkwargs 属性を持っています。

When the view is called during the request/response cycle, the setup() method assigns the HttpRequest to the view's request attribute, and any positional and/or keyword arguments captured from the URL pattern to the args and kwargs attributes, respectively. Then dispatch() is called.

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)Link to this definition

Performs key view initialization prior to dispatch().

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

dispatch(request, *args, **kwargs)Link to this definition

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

デフォルトの処理は、HTTP メソッドを調べて、その HTTP メソッドと一致するメソッドに処理を委ねるよう試みます; 例えば、GETget() に、POSTpost() に委ねられます。

デフォルトでは、HEAD リクエストは get() に委ねられます。HEAD リクエストを GET とは違う方法で操作する必要がある場合は、head() メソッドをオーバーライドすることができます。例えば その他の HTTP メソッドをサポートする をご覧ください。

http_method_not_allowed(request, *args, **kwargs)Link to this definition

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

プレーンテキストで、有効なメソッドのリストともに、HttpResponseNotAllowed を返すデフォルトの処理です。

options(request, *args, **kwargs)Link to this definition

OPTIONS HTTP 動詞のためのリクエストへのレスポンスを操作します。ビューの有効な HTTP メソッド名のリストを含む Allow ヘッダーとともにレスポンスを返します。

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.

TemplateViewLink to this heading

class django.views.generic.base.TemplateViewLink to this definition

URL 内でキャプチャされたパラメータを含むコンテキストとともに、与えられたテンプレートをレンダリングします。

継承元 (MRO)

このメソッドは、以下のビューからメソッドと属性を継承しています:

メソッドのフローチャート

  1. setup()

  2. dispatch()

  3. http_method_not_allowed()

  4. get_context_data()

Example views.py:

Code
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:

Code
from django.urls import path

from myapp.views import HomePageView

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

コンテキスト

  • (ContextMixin を通じて) ビューに対応した URL パターンからキャプチャされたキーワード引数とともに入力されます。

  • You can also add context using the extra_context keyword argument for as_view().

RedirectViewLink to this heading

class django.views.generic.base.RedirectViewLink to this definition

与えられた URL にリダイレクトします。

与えられた URL は、辞書形式の文字列フォーマットを含むかもしれず、URL 内でキャプチャされたパラメータに対して追加されます。キーワード追加は (たとえ引数が渡されなくとも) 常に 行われるため、Python がアウトプット上でパーセント文字に変換できるように、URL 内のすべての "%" 文字は "%%" と書かれなければなりません。

与えられた URL が None の場合、Djangoは HttpResponseGone (410) を返します。

継承元 (MRO)

このビューは、以下のビューからメソッドと属性を継承します:

メソッドのフローチャート

  1. setup()

  2. dispatch()

  3. http_method_not_allowed()

  4. get_redirect_url()

Example views.py:

Code
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:

Code
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'),
]

属性

urlLink to this definition

リダイレクト先の URL です。もしくは、410 (Gone) HTTP エラーを投げる None です。

pattern_nameLink to this definition

リダイレクト先の URL パターンの名前です。このビューのために渡されてきたものと同じ args と kwargs を使ってリバースされます。

permanentLink to this definition

リダイレクトがパーマネントかどうかを指定します。ここでの違いは、返される HTTP ステータスコードだけです。True の場合、リダイレクトはステータスコード 301 を使います。False の場合は、ステータスコード 302 を使います。デフォルトでは、permanentFalse です。

query_stringLink to this definition

GET クエリ文字列を新しい場所に渡すかどうかを指定します。True の場合、クエリ文字列は URL に追加されます。False の場合、クエリ文字列は破棄されます。 デフォルトでは、query_stringFalse です。

メソッド

get_redirect_url(*args, **kwargs)Link to this definition

リダイレクトのために、対象の URL を組み立てます。

The args and kwargs arguments are positional and/or keyword arguments captured from the URL pattern, respectively.

デフォルトの処理は、url を最初の文字列として使い、URLでキャプチャされた名前付きグループを使用したその文字列内の名前付き % パラメータの展開を実行します。

url がセットされていない場合、get_redirect_url() が URLでキャプチャされたものを使って pattern_name をリバースしようとします (名前あり・名前なしグループの両方が使われます)。

query_string によってリクエストされた場合、生成された URL にクエリ文字列を追加します。サブクラスは、メソッドがリダイレクト準備ができた URL 文字列を返す限り、これらが望むとおりの処理をします。