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:
max_age: The default is None. Sets the maximum age in seconds that the cookie should last. If it's None, the cookie expires when the browser is closed.
expires: The default is None. Specifies the date and time when the cookie will expire. Format is Wdy, DD-MM-YY HH:MM:SS GMT.
path: The default is /. Specifies a path prefix where the cookie is valid. The cookie is sent only to requests that begin with the path prefix.
domain: The default is None. Specifies the domain in which this cookie is valid.
secure: The default is False. If it's set to True, the browser should return the cookie only over HTTPS requests.