gpt4 book ai didi

python - 如何更改/添加 Django 的 ListView 的响应 header ?

转载 作者:太空宇宙 更新时间:2023-11-03 18:10:41 32 4
gpt4 key购买 nike

我正在尝试修改 ListView 的响应 header ,以解决似乎是缓存的问题。这是我正在尝试的:

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'

这显然发生在 MultipleObjectMixinget_context_data() 行上:

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

我应该采取什么不同的做法?如何更改 ListView 的响应 header ?

<小时/>

作为引用,这里是 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

最佳答案

在你的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

调用 super().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)

关于python - 如何更改/添加 Django 的 ListView 的响应 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26027255/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com