2014-09-24 49 views
1

我正在嘗試修改ListView的響應標頭以解決看起來像是緩存問題。下面是我想:如何修改/添加到Django的ListView的響應頭文件?

def get(self, request, *args, **kwargs): 
    context = super(MapListView, self.get_context_data(*args, **kwargs) # Errors here 
    response = super(MapListView, self).render_to_response(context, **kwargs) 
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" 
    response.headers["Pragma"] = "no-cache" 
    response.headers["Expires"] = "0" 
    return response 

我也試了一下:

def get(self, request, *args, **kwargs): 
    context = self.get_context_data() # Errors here 
    [. . . ] 

在這兩種情況下,這AttributeError拋出:

'MapListView" object has no attribute 'object_list' 

這顯然是發生在這條線get_context_data() from MultipleObjectMixin

queryset = kwargs.pop('object_list', self.object_list) 

我應該做什麼不同?我如何改變我的ListView的回覆標題?


作爲參考,這裏是whole get_context_data() definition


爲了獲得更大的參考,這是我的整個觀點:

class MapContactClientListView(ListView): 
    model = Map # Note: This isn't the real name, so it's not a problem with this. 
    cursor = connections["default"].cursor() 
    cursor.execute("""SELECT map.* 
         FROM map 
         INNER JOIN profile 
          ON (map.profile_id = profile.id) 
         ORDER BY profile.name""") 
    queryset = dictfetchall(cursor) 
    paginate_by = 20 
    template_name = 'onboardingWebApp/map_list.html' 

    def get(self, request, *args, **kwargs): 
     context = super(MapListView, self.get_context_data(*args, **kwargs) 
     response = super(MapListView, self).render_to_response(context, **kwargs) 
     response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" 
     response.headers["Pragma"] = "no-cache" 
     response.headers["Expires"] = "0" 
     return response 
+0

如果顯示整個類定義,但是從它的聲音來看,你從來沒有配置過'model'或'queryset'。 – Joseph 2014-09-24 22:04:32

+0

我確實配置了兩者。 :/我現在添加了整個定義。 – 2014-09-24 22:13:12

+0

將所有關於遊標和查詢集的東西移動到get_queryset()函數中(並使用return而不是設置queryset)。我很驚訝你沒有在那些直接的錯誤。 – Joseph 2014-09-24 22:14:29

回答

1

在你def get(self, request, *args, **kwargs):

def get(self, request, *args, **kwargs): 
    response = super(MapListView, self).get(request,*args,**kwargs) 
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" 
    response.headers["Pragma"] = "no-cache" 
    response.headers["Expires"] = "0" 
    return response 

超()的調用get()方法將正確設置object_list中,但它依賴於get_queryset。我不相信你已經正確設置了你的查詢集(因爲你正在動態設置它的類定義),所以我會將其更改爲:

def get_queryset(self): 
    cursor = connections["default"].cursor() 
    cursor.execute("""SELECT map.* 
        FROM map 
        INNER JOIN profile 
         ON (map.profile_id = profile.id) 
        ORDER BY profile.name""") 
    return dictfetchall(cursor) 
+0

非常好,謝謝!儘管我沒有最終需要它,但這對於未來的參考知道很好。 :) – 2014-09-24 23:00:49