2011-07-11 13 views
5

我跑到以下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時。

如何讓我的上下文處理器適用於所有請求?

回答

11

您已回答了您的問題。它適用於使用RequestContext的回覆。它不適用於那些沒有的。

將其應用於所有響應的方式是確保始終使用RequestContext。或者,在Django 1.3+中,您可以使用新的render快捷方式代替render_to_response,它爲您創建RequestContext。

0

僅當將RequestContext對象(使用當前請求初始化)作爲context_instance發送到模板時,上下文處理器變量纔可用。

+1

有沒有可以用來避免context_instance樣板的DRY快捷鍵?我假設一個很常見的情況是,你希望上下文處理器變量對所有請求都存在。假設所有觀點都包含需要列表「linked_sites」的頁腳。 「linked_sites」將由上下文處理器提供,但我想避免使用context_instance = RequestContext(request):-)來散佈我的代碼 – knorv

3

介紹的Django Django的1.3新render快捷方式自動包括RequestContext

from django.shortcuts import render 

def my_view(request): 
    # View code here... 
    context = { 
     'some_extra_var_for_template': 'value' 
    } 
    return render(request, 'myapp/index.html', context) 

您可以在Django docs讀到它。

相關問題