diff --git a/hitcount/mixins.py b/hitcount/mixins.py index 6cb66c7..b81bac8 100644 --- a/hitcount/mixins.py +++ b/hitcount/mixins.py @@ -53,6 +53,10 @@ def hit_count(request, hitcount): """ UpdateHitCountResponse = namedtuple( 'UpdateHitCountResponse', 'hit_counted hit_message') + # as of Django 1.8.4 empty sessions are not being saved + # https://code.djangoproject.com/ticket/25489 + if not request.session.session_key: + request.session.create() user = request.user diff --git a/tests/test_mixins.py b/tests/test_mixins.py index 6aab81e..95d3708 100644 --- a/tests/test_mixins.py +++ b/tests/test_mixins.py @@ -4,6 +4,7 @@ from django.contrib.auth.models import Group from django.contrib.auth.models import User +from django.contrib.sessions.backends.db import SessionStore from django.utils import timezone from hitcount.conf import settings @@ -28,6 +29,19 @@ def test_when_use_ip_is_disabled(self): hit = Hit.objects.last() self.assertIsNone(hit.ip) + def test_session_key_is_not_present(self): + session = SessionStore(session_key=None) + + self.request_post.session = session + + response = HitCountViewMixin.hit_count(self.request_post, self.hit_count) + + self.assertIs(response.hit_counted, True) + self.assertEqual(response.hit_message, 'Hit counted: session key') + # test database + hit = Hit.objects.last() + self.assertIsNotNone(hit.session) + def test_anonymous_user_hit(self): response = HitCountViewMixin.hit_count(self.request_post, self.hit_count)