Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for cookie existence in Django

Simple stuff here...

if I try to reference a cookie in Django via

request.COOKIE["key"]

if the cookie doesn't exist that will throw a key error.

For Django's GET and POST, since they are QueryDict objects, I can just do

if "foo" in request.GET

which is wonderfully sophisticated...

what's the closest thing to this for cookies that isn't a Try/Catch block, if anything...

like image 298
M. Ryan Avatar asked Sep 23 '09 15:09

M. Ryan


People also ask

How does Django find cookie value?

Django provides built-in methods to set and fetch cookie. The set_cookie() method is used to set a cookie and get() method is used to get the cookie. The request. COOKIES['key'] array can also be used to get cookie values.

Does Django use cookies by default?

Django uses a cookie containing a special session id to identify each browser and its associated session with the site. The actual session data is stored in the site database by default (this is more secure than storing the data in a cookie, where they are more vulnerable to malicious users).


2 Answers

request.COOKIES is a standard Python dictionary, so the same syntax works.

Another way of doing it is:

request.COOKIES.get('key', 'default')

which returns the value if the key exists, otherwise 'default' - you can put anything you like in place of 'default'.

like image 196
Daniel Roseman Avatar answered Oct 25 '22 14:10

Daniel Roseman


First, it's

request.COOKIES

not request.COOKIE. Other one will throw you an error.

Second, it's a dictionary (or, dictionary-like) object, so:

if "foo" in request.COOKIES.keys()

will give you what you need. If you want to get the value of the cookie, you can use:

request.COOKIES.get("key", None)

then, if there's no key "key", you'll get a None instead of an exception.

like image 24
kender Avatar answered Oct 25 '22 15:10

kender