Previous Page Next Page

Setting and Retrieving Cookies

Setting data in the user's session typically is the best way to keep persistent data. However, sometimes you'll want to add cookies to the browser to store data. Django provides the COOKIES attribute and the set_cookie() function to the HttpRequest object of the view functions to facilitate this.

The COOKIES attribute acts like a dictionary inside the request and includes the cookies sent in the request from the browser. For example, if you wanted to access the sessionid cookie created by Django, you could use the following line of code:

sessionID = request.COOKIES['sessionid']

Setting cookies requires using the set_cookies() function and passing it the cookie's identifier and value. For example, you could use the following code snippet to set in the browser a cookie named last_login with the current time value:

time = "%s" % datetime.now()
response.set_cookie('last_login', time)

Watch Out!

Never store important data in cookies. The data is accessible to just about everyone. If you do store values in cookies, make certain that the data is cleaned before you import it into your system.


The set_cookie() function also accepts the following parameters to configure the cookie:

Previous Page Next Page