[Django]-Set multiple cookies with the same name in Django

3👍

This may not be exact answer to the question, but still.

This seems issue with the django implementation, as it is only using cookie name as a key in dict.
In real world, one can have cookies with same name with multiple values, provided either domain or path differs. I found this useful HTTP cookies explained

More Reference:

RFC2965

Http Cookie

👤Rohan

3👍

It does use a simple dict to store the cookie, however when rendering the cookies to the response headers django simple iterates cookies.values() it doesn’t look at the keys.

To that end you CAN get fancy (this is python 3.5):

# python 3.5 specific unpacking
# Note that according to the RFC, cookies ignore the ports

hostname, *_ = request.get_host().split(':')

# set the cookie to delete
response.delete_cookie(settings.ACCESS_TOKEN_COOKIE_KEY,
                       domain=settings.COOKIE_DOMAIN)
# pull it out of the cookie storage
# and delete it so we can write an new one
cookie_domain_cookie = response.cookies[settings.ACCESS_TOKEN_COOKIE_KEY]
del response.cookies[settings.ACCESS_TOKEN_COOKIE_KEY]

# write the new cookie
response.delete_cookie(settings.ACCESS_TOKEN_COOKIE_KEY,
                       domain=hostname)

# do the same as we did above, probably not strictly necessary
hostname_cookie = response.cookies[settings.ACCESS_TOKEN_COOKIE_KEY]
del response.cookies[settings.ACCESS_TOKEN_COOKIE_KEY]

# make new keys for the cookies
cookie_domain_cookie_key = "{}:{}".format(settings.ACCESS_TOKEN_COOKIE_KEY, settings.COOKIE_DOMAIN)
hostname_cookie_key = "{}:{}".format(settings.ACCESS_TOKEN_COOKIE_KEY, hostname)

# set them
response.cookies[cookie_domain_cookie_key] = cookie_domain_cookie
response.cookies[hostname_cookie_key] = hostname_cookie

Leave a comment