Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django how to get Response in class based view

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
like image 677
djangochina Avatar asked Sep 18 '13 15:09

djangochina


People also ask

How do you use decorators in class-based views in Django?

To do this you apply the decorator to the dispatch() method of the class. The decorators will process a request in the order they are passed to the decorator. In the example, never_cache() will process the request before login_required() . In this example, every instance of ProtectedView will have login protection.

What can a Django view return?

Django views are Python functions that takes http requests and returns http response, like HTML documents. A web page that uses Django is full of views with different tasks and missions.

Which is better class-based view or function-based view Django?

We have mentioned that class-based views don't replace function-based views. In some cases, function-based views are better and in some cases, class-based views are better. In the implementation of the list view, you can get it working by subclassing the ListView and overriding the attributes.


1 Answers

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.

like image 85
jproffitt Avatar answered Sep 19 '22 05:09

jproffitt