django如何获取基于类的视图中的Response [英] django how to get Response in class based view
问题描述
现在我有一个基于类的视图。并且我想在这个视图中设置cookie,但我可以得到响应,但响应返回的get methond .so我不能设置cookie到response.so如何获取Response在基于类的视图
now i have a class-based view. and i want to set cookie in this view,but i can get the response,but the response is returned in the get methond .so i can not set the cookie to response.so how to get Response in class based view
class MyView(TemplateView):
def get_context_data(self, **kwargs):
context = super(UBaseTemplateView, self).get_context_data(**kwargs)
#in here set cookie,but can get the response
#response.set_cookie("success","success")
return context
推荐答案
code>请求,仅在响应
,但burhan-khalid正确的方向。 get_context_data
只返回一个字典,因此您无法访问该响应。您必须在 dispatch
或 TemplateView
中在 render_to_response
。这里是一个例子:
You cannot set_cookie on a request
, only on response
, but burhan-khalid was going in the correct direction. get_context_data
only returns a dictionary, so you cannot access the response there. You have to access it either in dispatch
, or with a TemplateView
, in render_to_response
. Here is an example:
class MyView(TemplateView):
def render_to_response(self, context, **response_kwargs):
response = super(MyView, self).render_to_response(context, **response_kwargs)
response.set_cookie("success","success")
return response
我建议你不要在 get_context_data
。您可能需要重构以获取您在 render_to_response
中设置的Cookie。
I would suggest you shouldn't do all your processing code in get_context_data
. You may need to refactor to get the cookie you want set in render_to_response
.
这篇关于django如何获取基于类的视图中的Response的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!