Base views¶
以下の3つのクラスは、Django のビューの作成に必要な多くの機能を提供します。これらは Django ビューの 親の ビューと見なすことができ、それ自体で使うことも継承して使うこともできます。プロジェクトに必要な全ての機能を提供するわけではありませんが、その場合は Mixins と汎用クラスベースビューが使えます。
多くの Django のビルトインのクラスベースビューは、ほかのクラスベースビューや多種の mixin を継承しています。この継承チェーンは非常に重要なため、原型のクラスは 継承元 (MRO) セクションにドキュメントがあります。MRO は メソッド解決順序 (Method Resolution Order) の略です。
View
¶
-
class
django.views.generic.base.
View
¶ 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
.メソッドのフローチャート
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"), ]
属性
-
http_method_names
¶ このビューが受け入れる HTTP メソッドの名称のリストです。
デフォルト値:
["get", "post", "put", "patch", "delete", "head", "options", "trace"]
メソッド
-
classmethod
as_view
(**initkwargs)¶ リクエストを受け取ってレスポンスを返す、呼び出し可能なビューを返します:
response = MyView.as_view()(request)
返されたビューは、
view_class
とview_initkwargs
属性を持っています。When the view is called during the request/response cycle, the
setup()
method assigns theHttpRequest
to the view'srequest
attribute, and any positional and/or keyword arguments captured from the URL pattern to theargs
andkwargs
attributes, respectively. Thendispatch()
is called.If a
View
subclass defines asynchronous (async def
) method handlers,as_view()
will mark the returned callable as a coroutine function. AnImproperlyConfigured
exception will be raised if both asynchronous (async def
) and synchronous (def
) handlers are defined on a single view-class.Changed in Django 4.1:Compatibility with asynchronous (
async def
) method handlers was added.
-
setup
(request, *args, **kwargs)¶ Performs key view initialization prior to
dispatch()
.If overriding this method, you must call
super()
.
-
dispatch
(request, *args, **kwargs)¶ The
view
part of the view -- the method that accepts arequest
argument plus arguments, and returns an HTTP response.デフォルトの処理は、HTTP メソッドを調べて、その HTTP メソッドと一致するメソッドに処理を委ねるよう試みます; 例えば、
GET
はget()
に、POST
はpost()
に委ねられます。デフォルトでは、
HEAD
リクエストはget()
に委ねられます。HEAD
リクエストをGET
とは違う方法で操作する必要がある場合は、head()
メソッドをオーバーライドすることができます。例えば その他の HTTP メソッドをサポートする をご覧ください。
-
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.
プレーンテキストで、有効なメソッドのリストともに、
HttpResponseNotAllowed
を返すデフォルトの処理です。
-
options
(request, *args, **kwargs)¶ 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 withawait
.Changed in Django 4.1:Compatibility with classes defining asynchronous (
async def
) method handlers was added.
-
TemplateView
¶
-
class
django.views.generic.base.
TemplateView
¶ URL 内でキャプチャされたパラメータを含むコンテキストとともに、与えられたテンプレートをレンダリングします。
継承元 (MRO)
このメソッドは、以下のビューからメソッドと属性を継承しています:
django.views.generic.base.TemplateResponseMixin
django.views.generic.base.ContextMixin
django.views.generic.base.View
メソッドのフローチャート
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"), ]
コンテキスト
- (
ContextMixin
を通じて) ビューに対応した URL パターンからキャプチャされたキーワード引数とともに入力されます。 - You can also add context using the
extra_context
keyword argument foras_view()
.
RedirectView
¶
-
class
django.views.generic.base.
RedirectView
¶ 与えられた URL にリダイレクトします。
与えられた URL は、辞書形式の文字列フォーマットを含むかもしれず、URL 内でキャプチャされたパラメータに対して追加されます。キーワード追加は (たとえ引数が渡されなくとも) 常に 行われるため、Python がアウトプット上でパーセント文字に変換できるように、URL 内のすべての
"%"
文字は"%%"
と書かれなければなりません。与えられた URL が
None
の場合、DjangoはHttpResponseGone
(410) を返します。継承元 (MRO)
このビューは、以下のビューからメソッドと属性を継承します:
メソッドのフローチャート
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", ), ]
属性
-
url
¶ リダイレクト先の URL です。もしくは、410 (Gone) HTTP エラーを投げる
None
です。
-
pattern_name
¶ リダイレクト先の URL パターンの名前です。このビューのために渡されてきたものと同じ args と kwargs を使ってリバースされます。
-
permanent
¶ リダイレクトがパーマネントかどうかを指定します。ここでの違いは、返される HTTP ステータスコードだけです。
True
の場合、リダイレクトはステータスコード 301 を使います。False
の場合は、ステータスコード 302 を使います。デフォルトでは、permanent
はFalse
です。
-
query_string
¶ GET クエリ文字列を新しい場所に渡すかどうかを指定します。
True
の場合、クエリ文字列は URL に追加されます。False
の場合、クエリ文字列は破棄されます。 デフォルトでは、query_string
はFalse
です。
メソッド
-
get_redirect_url
(*args, **kwargs)¶ リダイレクトのために、対象の URL を組み立てます。
The
args
andkwargs
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 文字列を返す限り、これらが望むとおりの処理をします。
-