2014-09-24 120 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