シンプルなミックスイン (mixin)

ContextMixin

class django.views.generic.base.ContextMixin

属性

extra_context

コンテキストに含める辞書。これは、as_view() の中でコンテキストを指定する便利な方法です。使用例を次に示します。

from django.views.generic import TemplateView

TemplateView.as_view(extra_context={"title": "Custom Title"})

メソッド

get_context_data(**kwargs)

テンプレートコンテキストを表す辞書を返します。与えられたキーワード引数は、返されるコンテキストを構成します。使用例を次に示します。

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context["number"] = random.randrange(1, 100)
    return context

すべてのクラスベースのジェネリックビューのテンプレートコンテキストには、View インスタンスを指す view 変数が含まれています。

適切な場合には alters_data を使用する

Note that having the view instance in the template context may expose potentially hazardous methods to template authors. To prevent methods like this from being called in the template, set alters_data=True on those methods. For more information, read the documentation on rendering a template context.

TemplateResponseMixin

class django.views.generic.base.TemplateResponseMixin

適切なコンテキストを指定して TemplateResponse を構築するメカニズムを提供します。使用するテンプレートは設定可能で、サブクラス化によりさらにカスタマイズできます。

属性

template_name

文字列で指定された使用するテンプレートの完全な名前。template_name を定義しないと、django.core.exceptions.ImproperlyConfigured 例外が発生します。

template_engine

テンプレートを読み込む際に使用するテンプレートエンジンの NAME です。 template_engineresponse_classusing キーワード引数として渡されます。デフォルトは None で、 Django は設定された全てのエンジンでテンプレートを検索します。

response_class

render_to_response メソッドが返す response クラス。 デフォルトは TemplateResponse です。 TemplateResponse インスタンスのテンプレートとコンテキストは後で変更できます (たとえば template response ミドルウェア で変更できます)。

カスタムテンプレートの読み込みやカスタムコンテキストオブジェクトのインスタンス化が必要な場合は、 TemplateResponse サブクラスを作成して response_class に代入してください。

content_type

レスポンスに使用するコンテンツタイプ。 content_typeresponse_class のキーワード引数として渡されます。デフォルトは None で、その場合 Django は 'text/html' を使用します。

メソッド

render_to_response(context, **response_kwargs)

self.response_class インスタンスを返します。

キーワード引数を指定すると、response クラスのコンストラクタに渡されます。

Calls get_template_names() to obtain the list of template names that will be searched looking for an existent template.

get_template_names()

テンプレートをレンダリングする際に検索するテンプレート名のリストを返します。最初に見つかったテンプレートが使用されます。

デフォルトの実装では、template_name を含むリストを返します(指定された場合)。