Question

I guess this question is very lame, but I actually tried everything before posting. All the questions alike on SO are not answered.

My code goes like:

@csrf_protect
def login_view(request):
    if request.method == "GET":
        return HttpResponse(json.dumps(
                   {'username':request.user.username}
               ), mimetype='application/json')

Django needs to add a Set-Cookie header to the response when serving this view, but it doesn't. The csrftoken cookie is not there after I get a response from this view, and it's not in the headers. CSRFMiddleware is on and works for other parts of the site. How do I get Django to set the cookie?

Please, help!

Was it helpful?

Solution

Django does not set the cookie value to response headers when it return json data,so you need to set cookie value in response object manually. code like this:

@csrf_protect
def login_view(request):
    if request.method == "GET":
        response =  HttpResponse(json.dumps(
                   {'username':request.user.username}
               ), mimetype='application/json')

        response.set_cookie('hello','world')
        return response
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top