Entries published on December 22, 2023
Set cookies the right way
This is part of a series of posts I’m doing as a sort of Python/Django Advent calendar, offering a small tip or piece of information each day from the first Sunday of Advent through Christmas Eve. See the first post for an introduction.
Cookies in the cookie jar
Django’s request and response objects, and their attributes and methods, make dealing with cookies easy. You can read from the
request.COOKIES dictionary to get a cookie, and you can use the response’s
set_cookie() method to set cookies. What else do you need?
Well, potentially a few things.
First of all, it’s worth reviewing those arguments to
set_cookie(), because several of them are important. You should probably always set:
secure=True: This instructs browsers to only send the cookie on secure (i.e., HTTPS) requests, never on unencrypted connections. This helps avoid some potential leaks of cookie values — for example, if the user …