Django Sessions in StaticLiveServerTestCase

This is for Django 1.8.

Here was the scenario. I have a Django site where most of the pages require the user to login. I have a form that gets some initial values from Django sessions. The form has lots of javascript, so live testing seemed best. The problem I could not set the session values in the test code.

Initially, this seemed pretty easy because in the test code, there was a variable called:


However, changes to the session were not present when the test code called the view. Careful inspection showed that the session id’s in self.client.session and view.request.session were different.

Adding the following method to StaticLiveServerTestCase solved the problem:

    def save_to_session(self, key, value):
        cookies = self.selenium.get_cookies()
        session_key = None
        for cookie in cookies:
            if cookie[u'name'] == u'sessionid':
                session_key = cookie[u'value']

        if session_key:
            from django.contrib.sessions.backends.cached_db import SessionStore
            s = SessionStore(session_key)
            s[key] = value



Working Directly with Sessions in Django

I store lots of user defined default values in the Django (1.7) sessions. When there is a bug sometimes a bad value can get saved into the user session and cause ongoing problems.

One way I solved the problem was to create a view to allow the user to clear his own cache.

def clear_session(request):
    return HttpResponse('Session was flushed.')

While that seems incredibly easy to use, it still flusters some users. So I created a view that lets me clear that users session. When I get an Django error message by email, it includes the user’s session id. I use this to call this view:

from django.contrib.sessions.backends.db import SessionStore
def clear_session(request, session_id):
    if not request.user.is_superuser:
        return HttpResponseForbidden('Forbidden')

        session = SessionStore(session_key=session_id)
    except ObjectDoesNotExist:
        session = None

    if session:
        keys = session.keys()
        for key in keys:
            # Don't delete protected keys.
            if key[0] != '_' and key != 'testcookie':
                del session[key]
    return HttpResponseRedirect(reverse('show_user_from_session', args=[session_id]))

With this view, I can manually clear the user’s session without logging them off. Then I can confirm the session is cleared, before notifying them of the fix.