The problem that you face relates partly to Django, but firstly to the properties of HTTP cookies mechanism itself.
A cookie valid for a path is also valid for all its subpaths (a query string doesn't matter). So last_visit
cookie intended for /
is also valid for /view2/
. For specifics of the matching mechanism, defining whether a cookie is suitable for a path, see subsection "5.1.4. Paths and Path-Match" in RFC6265.
So both cookies are sent, and the order in which they are listed in Cookie:
HTTP header is from more specific paths to less specifics ones. See over here in RFC6265.
Now, Django processes cookies from the header one by one and populates a plain python dictionary request.COOKIES
, rewriting values when keys are already present. That is how your value for last_visit
is rewriten when both cookies for both paths are sent in http request.
While Django processes cookies like that, though it would be more reasonable to only keep the first (not the last) value for the key as it relates to more specific path, you can fix the issue by only using the same cookie names for paths of the same level -- for /root/view1/
and /root/view2/
, but not for /root/
. Or You can divert cookie names with respect to http path like that:
import hashlib
cookie_name = 'last_visit%s' % hashlib.md5(request.path).hexdigest()
# ...
cookie = request.COOKIES.get(cookie_name)
# ...
response.set_cookie(cookie_name, cookie, path=request.path)