I use django auth for my website, which needs to have the session middleware installed.
Django session middleware always adds a session cookie, even for anonymous us
Session data is set in the cookie in the process_response
of SessionMiddleware
. This function doesn't use any setting or request.user
, so you do not have any way of knowing inside this method whether the user is a logged in user or an anonymous user. So, you can't disable sending the session cookie to the browser.
However if you want this functionality then you can subclass SessionMiddleware
and overide process_response
.
from django.contrib.sessions.middleware import SessionMiddleware
from django.conf import settings
class NewSessionMiddleware(SessionMiddleware):
def process_response(self, request, response):
response = super(NewSessionMiddleware, self).process_response(request, response)
#You have access to request.user in this method
if not request.user.is_authenticated():
del response.cookies[settings.SESSION_COOKIE_NAME]
return response
And you can use your NewSessionMiddleware
in place of SessionMiddleware
.
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'myapp.middleware.NewSessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.doc.XViewMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
)