我跑到以下Django模板上下文處理器問題。爲什麼此Django模板上下文處理器不適用於所有請求?
上下文處理器在myapp/context_processors.py
定義:
def my_context_processor(request):
return {
'foo': 123,
}
它在settings.py有線了連同標準的Django上下文處理器:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'myproject.myapp.context_processors.my_context_processor',
)
我遇到的問題是, my_context_processor不適用於所有請求。
它不是爲下面的代碼應用:
def index(request):
return render_to_response("index.html", locals())
然而,它是爲下面的代碼應用:
def index(request):
return render_to_response("index.html", locals(), context_instance=RequestContext(request))
我的印象是這方面的處理器正在申請所有請求,而不僅僅是當提供context_instance
時。
如何讓我的上下文處理器適用於所有請求?
有沒有可以用來避免context_instance樣板的DRY快捷鍵?我假設一個很常見的情況是,你希望上下文處理器變量對所有請求都存在。假設所有觀點都包含需要列表「linked_sites」的頁腳。 「linked_sites」將由上下文處理器提供,但我想避免使用context_instance = RequestContext(request):-)來散佈我的代碼 – knorv