89

特定の変数をすべてのビュー (主にカスタム認証タイプの変数) に渡す必要があるところまで来ました。

これを行うには、独自のコンテキスト プロセッサを作成するのが最善の方法であると言われましたが、いくつか問題があります。

私の設定ファイルは次のようになります

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.contrib.messages.context_processors.messages",
    "sandbox.context_processors.say_hello", 
)

ご覧のとおり、「context_processors」というモジュールと、その中に「say_hello」という関数があります。

どのように見える

def say_hello(request):
        return {
            'say_hello':"Hello",
        }

ビュー内で次のことができるようになったと仮定するのは正しいですか?

{{ say_hello }}

現在、これは私のテンプレートでは何もレンダリングされません。

私のビューは次のようになります

from django.shortcuts import render_to_response

def test(request):
        return render_to_response("test.html")
4

5 に答える 5

55

作成したコンテキスト プロセッサが動作するはずです。問題はあなたの見解にあります。

ビューが でレンダリングされていることに確信がありRequestContextますか?

例えば:

def test_view(request):
    return render_to_response('template.html')

上記のビューは、 にリストされているコンテキスト プロセッサを使用しませんTEMPLATE_CONTEXT_PROCESSORSRequestContext次のようなものを提供していることを確認してください。

def test_view(request):
    return render_to_response('template.html', context_instance=RequestContext(request))
于 2010-05-23T22:23:58.110 に答える
31

django docsによるrenderと、 context_instance 引数を使用して render_to_response の代わりにショートカットとして使用できます。

または、render()RequestContext の使用を強制する context_instance 引数を指定した render_to_response() の呼び出しと同じショートカットを使用します。

于 2012-10-24T15:25:15.410 に答える