2016-06-11 36 views
1

我在Django項目中使用自己的模板(即/project/app1/template,/project/app2/template等)有幾個應用程序。在應用程序模板中啓用上下文處理器

但是,模板上下文處理器(在主應用程序/項目的settings.py中定義)在這些應用程序模板中不可用。

我必須手動設置context_instance爲了使兒童模板context處理器(否則背景處理器從模板中丟失):

from django.template import RequestContext 

def index(request): 
    return render_to_response('index.html', {}, context_instance=RequestContext(request)) 

這裏是我的settings.py

PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__)) 
BASE_DIR = PACKAGE_ROOT 


TEMPLATES = [ 
    { 
     "DIRS": [ 
      os.path.join(PACKAGE_ROOT, "templates"), 
     ], 
     "APP_DIRS": True, 

     "OPTIONS": { 
      ... 
      "context_processors": [ 
       "django.contrib.auth.context_processors.auth", 
       "django.template.context_processors.request", 
       ... 
      ], 
     }, 
    }, 
] 

如何我是否可以在應用模板中訪問上下文處理器,而無需在每個視圖函數中手動注入context_instance

回答

1

這與「app templates」沒有任何關係;無論您的模板位於何處,行爲都完全相同。

如果您希望運行上下文處理器,您總是需要一個RequestContext;除此之外,這是因爲它們傳遞了請求對象,所以它需要存在。

然而存在這樣創建的RequestContext快捷方式,那就是render功能:

def index(request): 
    return render(request, 'index.html', {}) 

注意,這需要請求作爲第一個參數。

相關問題