Index: contrib/sessions/middleware.py =================================================================== --- contrib/sessions/middleware.py (revision 4872) +++ contrib/sessions/middleware.py (working copy) @@ -68,10 +68,21 @@ _session = property(_get_session) class SessionMiddleware(object): + def __init__(self): + self.exception_occured = False + def process_request(self, request): request.session = SessionWrapper(request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)) + def process_exception(self, request, exception): + self.exception_occured = True + def process_response(self, request, response): + # Don't try to save session when process method raised an exception. In case of database exceptions + # it may not even be possible. See ticket #3881. + if self.exception_occured: + return response + # If request.session was modified, or if response.session was set, save # those changes and set a session cookie. try: