2012-08-16 25 views
0

這些函數應該不能完全相同?模板上的direct_to_template和render_to_response - {{request}}

def IndexView(request): 
    return direct_to_template(request, template='index.html') 

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

我不要求在兩者之間的差別,但是爲什麼我的模板不能使用{{要求}}當我用使用direct_to_template ... 我讀了很多類似的問題,但我還沒有無法弄清楚。

有誰知道爲什麼?謝謝,

回答

2

的原因是,direct_to_template實際上是默認使用RequestContext(request)(像所有的通用視圖),這意味着你的所有的模板上下文處理器在模板(包括django.core.context_processors.request這是什麼使request變量訪問)可供選擇。

當您使用RequestContext時,它會掃描所有模板上下文處理器(如TEMPLATE_CONTEXT_PROCESSORS in your settings.py中所定義)並自動將它們添加到上下文中,以便它們在您的模板中可用。從文檔:

第二個不同之處在於它根據您的TEMPLATE_CONTEXT_PROCESSORS設置自動使用幾個變量填充上下文。

-1

您需要將django.core.context_processors.request添加到settings.py中的TEMPLATE_CONTEXT_PROCESSORS。

相關問題