django how to get Response in class based view

為{幸葍}努か 提交于 2019-12-12 11:08:31

问题


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

回答1:


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

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.



来源:https://stackoverflow.com/questions/18875803/django-how-to-get-response-in-class-based-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!