django: Set cookie expire time

Within your view, you can control certain aspects of the browser cookie. To do so, you access the set_cookie() method from within the HttpResponse object.

First, calculate the date/time when you wish the cookie to expire.

tomorrow = datetime.datetime.now() + datetime.timedelta(days = 1)
tomorrow = datetime.datetime.replace(tomorrow, hour=0, minute=0, second=0)
expires = datetime.datetime.strftime(tomorrow, "%a, %d-%b-%Y %H:%M:%S GMT")

Next, make sure you get access to the HttpResponse object.

#Response object
response = render_to_response('path/to/template.html', your_context_data, context_instance = RequestContext(request))

Finally, make a call to set_cookie() so you can set the expires arg.

# Cookie expires at the end of the day
response.set_cookie('read_count_%s' % content_type.id, value = read_count, expires = expires)

Sources

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog