2010-08-31 50 views
7

我使用的是django通用視圖,如何訪問我的模板中的請求。Django通用視圖 - 訪問請求

網址:

file_objects = { 
    'queryset' : File.objects.filter(is_good=True), 
} 
urlpatterns = patterns('', 
    (r'^files/', 'django.views.generic.list_detail.object_list', dict(file_objects, template_name='files.html')), 
) 

回答

9

經過一番更多搜尋,一邊等待人來回復此。我發現:

您需要添加到您的settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request', 
) 

這意味着,在默認情況下請求將被傳遞到所有的模板!

+3

並不完全正確 - 它會被傳遞到正在使用'RequestContext',所有通用視圖渲染的所有模板。 – 2010-08-31 09:14:40

+0

這對我來說並不奏效,四年半後使用Django 1.7。實際上1.7文檔在https://docs.djangoproject.com/en/1.7/ref/settings/頂部有一個警告 - 「在覆蓋設置時要小心,特別是當默認值是非空元組時或字典,比如MIDDLEWARE_CLASSES和TEMPLATE_CONTEXT_PROCESSORS。確保你保留了你想使用的Django功能所需的組件。「然而,看到這裏的解決方案:http://stackoverflow.com/questions/9899113/get-request-session-from-a-class-based-generic-view – Chirael 2015-02-04 02:36:56

1

我什麼工作是添加:

TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth", 
          "django.core.context_processors.request", 
          ) 

所涉及的settings.py沒有到urls.py

3

無答案的給出解決我的問題,所以對於那些其他人誰絆倒在通用視圖模板內這個希望訪問請求對象,你可以做這樣的事情在你的urls.py:

from django.views.generic import ListView 

class ReqListView(ListView): 
    def get_context_data(self, **kwargs): 
     # Call the base implementation first to get a context 
     c = super(ReqListView, self).get_context_data(**kwargs) 
     # add the request to the context 
     c.update({ 'request': self.request }) 
     return c 

url(r'^yourpage/$', 
    ReqListView.as_view(
     # your options 
    ) 
) 

乾杯!

3

嘗試使用get_queryset方法。

def get_queryset(self): 
    return Post.objects.filter(author=self.request.user) 

見鏈接(希望它可以幫助): - See Greg Aker's page...

+0

太棒了!這在Django中非常糟糕。我完全需要請求obj。在Listview子類中。 – Timo 2014-10-29 20:09:55