Setting cookies in an AJAX call using Django

I have a Django website and am trying to set a cookie in response to an AJAX call. I put the question more general, since now someone was responding to Cookies not working with AJAX call from jQuery in Django

On the client side, I have a JavaScript function that sends a GET request to the URL:

$.ajax({ url: url, success: function(data) { alert('Load was performed.'); } }); 

On the server side, I have the code setting the cookie:

 def vote(request, slug, rating): # Some irrelevant code... response = HttpResponse('Vote changed.') response.set_cookie('vote', 123456) return response 

I get the answer in jQuery code, but the problem is that the cookie is never set in the browser.

What am I doing wrong?

Thanks!

+4
source share
1 answer

Try creating a cookie with an expiration date, for example:

 var max_age = 14*24*60*60 # two weeks expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT") response.set_cookie('vote', 123456, max_age=max_age, expires=expires) 

Sorry if this example doesn’t work a bit - it's been a while since I worked with Django and I had to use Google cookie / date.

+3
source

Source: https://habr.com/ru/post/1385140/


All Articles