I am working on a Django project.I want to make a UI preference persist whether a user is logged in or logged out.
So cookies is the way i suppose. So i am confused whether request.COOKIES
in python and document.cookie
in JS is the same thing.
I mean for getting and setting cookie value would it be same if i do from JS or a Django view.
I hope my question is clear. I am kind of new to subject of cookies.
Thanks
request.COOKIES
and document.cookie
contain the same set of data; however, the ways of getting and setting cookie values are totally different.
request.COOKIES
is a python dict for you to read cookie. For example, you have a cookie named "color" and its value is "blue", when you do request.COOKIES['color']
, you get string "blue" back. You can't use request.COOKIES
to set cookie, because these cookie values are sent by browser to django when browser makes request. To set cookie, you need to use HttpResponse.set_cookie
. (https://docs.djangoproject.com/en/1.5/ref/request-response/#django.http.HttpResponse.set_cookie)]
document.cookie
, on the other hand, is the cookies in the "raw" format, which is a string of semicolon separated name-value pairs. To read a specific cookie, you need to perform a search on that string to find the cookie you're looking for; to set a cookie, you need to call document.cookie = "name=value;..."
[ref]. But most of the time, JavaScript libraries/frameworks have already done the dirty work for you, so to get/set cookie should be just a set of function calls.
request.COOKIES
returns
A standard Python dictionary containing all cookies. Keys and values are strings.
anddocument.cookie
returns a string
I think its more easy to iterate over an dictionary and get all the cookies than parse the string returned by javascript
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With