pete
pete

Reputation: 2799

Django: How to set a (permanent) cookie, in addition to temp session, in Class based views?

I'm using class-based views in my Django apps, where I'm returning a render() function, with the required context, like so:

class SignUpView(View):

    def get(self, request):

        # code...

        template = 'pages_fixed/accounts/' + insights.get_user_funnel( self, 'signup_page' )

        context = {
            'plans':          plans,
            'form':           form,
            'restore_inputs': self.request.session['restore_inputs'],
        }

        return render( request, template, context )

I'm already using Django's backend-based session mechanism to store various data with a set expiry date (these need to expire).

In addition, I need to be able to set (and later read) a separate, more permanent cookie. I found a post about doing it using the response object but how would I structure it in a Class-based view? Not really sure where to start, not seeing any examples in the docs? Is it possible?

Upvotes: 1

Views: 835

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599936

There's nothing complicated here, and certainly nothing that is different because you are using a class-based view. In fact, the way you are using the CBV it is almost completely identical to a function-based view, and you can set the cookie on the response in exactly the same way.

response = render(request, template, context)
response.set_cookie('my_cookie', 'my_cookie_value')
return response

Upvotes: 1

Related Questions