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:
self.client.session
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'] break if session_key: from django.contrib.sessions.backends.cached_db import SessionStore s = SessionStore(session_key) s[key] = value s.save()
Advertisements