I can not make sessions work. Django complains that HttpRequest objects do not have an attribute called "session". The documentation clearly states that if you have middleware and django.contrib.sessions in your installed applications, then you're good to go. I get this error using unit tests.
In my views.py:
def home_page(request): response = render(request, 'home.html', {'message_text' : request.session.get('message_text', ''), 'ip_address' : request.session.get('ip_address', ''), 'port_number' : request.session.get('port_number', ''), 'command_text' : request.session.get('command_text', ''),}) request.session['message_text'] = '' return response
The session values I'm trying to get are the ones I'm trying to set in my post post method elsewhere in views.py.
It also states that they are enabled by default for new projects. So I created a new django project and checked the session attribute in the console. Here is what I did:
(django1.5)Python $ django-admin.py startproject testing (django1.5)Python $ cd testing/ (django1.5)testing $ python manage.py shell Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.http import HttpRequest >>> r = HttpRequest() >>> r.session Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'HttpRequest' object has no attribute 'session' >>>
What am I missing?
UPDATE: This only happens when testing with unit tests. Here is a test that throws an exception:
def test_home_page_returns_correct_html(self): request = HttpRequest() response = home_page(request) expected_html = render_to_string('home.html') self.assertEqual(response.content, expected_html)