[Solved]-Setting a cookie in Django Rest Framework API

13👍

It happens because the response in which you are setting the cookie is never sent to the browser, thus no cookie is set. Note the changes below

@api_view(['GET'])
def cookies(request):
    if request.method == 'GET':
        if 'cookie' in request.COOKIES:
            value = request.COOKIES['cookie']
            response = HttpResponse('Works')
            return response
        else:
            response = HttpResponse('Does Not Works')
            response.set_cookie('cookie', 'MY COOKIE VALUE')
            return response

when you run it first time it will show ‘Does Not Work’ since the cookie is not set yet so if condition will fail, but in second time it would work.

6👍

You set cookies in response:

response.set_cookie('cookie', 'MY COOKIE VALUE')

but use if in reqeust cookies

if 'cookie' in request.COOKIES:

Leave a comment