Chidananda Nayak
Chidananda Nayak

Reputation: 1201

django set cookie and delete cookie

I am setting a cookie in django without response. when user logs in i trigger an api to authenticate its data and then i am trying to save its user_id in cookie in a class and then in another class am trying to delete the cookie means user is logged out.

class APIloginView(View):

    def get(self):
        r = requests.post(url,parameters)
        if 'user_id' not in request.COOKIES:
            request.COOKIES['user_id']='2133212332'
        print(request.COOKIES.get('user_id'))
    return HttpResponse(r)

but when i try to access in value in another class it is showing me none

class logout(View):
    def get(self):
        print(request.COOKIES.get('user_id'))
        pass

Where am i doing wrong?and i know deleting a session like del request.session['user_id'],how to delete a particular cookie?

Upvotes: 2

Views: 729

Answers (1)

Vaibhav Vishal
Vaibhav Vishal

Reputation: 7108

Cookie needs to be set on response you are returning.

def get(self, request):
    r = requests.post(url,parameters)
    response = HttpResponse(r)
    response.set_cookie('user_id', '2133212332')
    return response

Also how come your code is even working. You are trying to access request everywhere, but it doesn't exists, because your get has no request parameter. What you mean to do is:

def get(self, request):
    ...

Upvotes: 2

Related Questions