M. Ryan
M. Ryan

Reputation: 7182

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...

Upvotes: 8

Views: 13100

Answers (2)

kender
kender

Reputation: 87131

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.

Upvotes: 8

Daniel Roseman
Daniel Roseman

Reputation: 599450

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'.

Upvotes: 23

Related Questions