27 August 2010

Setting and Reading Cookies in python Django

I recently tried to figure out how to set and get cookie values.  I knew how to do sessions, but I wanted to have my own custom cookie.  I was looking for a key-value pairs I could let it be stored on user's browser instead of on the database which is the case with sessions.

Here's how to set a cookie.

response.set_cookie(key="mykey", value="myvalue")

Here's how to read the cookie.


if "mykey" in request.COOKIES:
     read_value = request.COOKIES["mykey"]


That's it.  Have fun with cookies.

Reference : http://docs.djangoproject.com/en/dev/ref/request-response/

No comments:

Post a Comment