From 2349cbd909c387d2d05cda20ce8d0c63c1b1c6c4 Mon Sep 17 00:00:00 2001 From: Ramon Saraiva Date: Tue, 25 Sep 2018 18:16:21 -0300 Subject: [PATCH] Fixed #29782 -- Added better error message when filtering queryset with AnonymousUser. --- AUTHORS | 1 + django/contrib/auth/models.py | 3 +++ tests/auth_tests/test_models.py | 8 ++++++++ 3 files changed, 12 insertions(+) diff --git a/AUTHORS b/AUTHORS index e9878e7e57..bc2e6bac5f 100644 --- a/AUTHORS +++ b/AUTHORS @@ -694,6 +694,7 @@ answer newbie questions, and generally made Django that much better: Ramez Ashraf Ramin Farajpour Cami Ramiro Morales + Ramon Saraiva Ram Rachum Randy Barlow Raphaƫl Barrois diff --git a/django/contrib/auth/models.py b/django/contrib/auth/models.py index 3e28da2ad4..6603fbafb8 100644 --- a/django/contrib/auth/models.py +++ b/django/contrib/auth/models.py @@ -383,6 +383,9 @@ class AnonymousUser: def __hash__(self): return 1 # instances always return the same hash value + def __int__(self): + raise TypeError('Cannot cast AnonymousUser to int. Are you trying to use it in place of User?') + def save(self): raise NotImplementedError("Django doesn't provide a DB representation for AnonymousUser.") diff --git a/tests/auth_tests/test_models.py b/tests/auth_tests/test_models.py index 755511bbb4..7bee3d7d31 100644 --- a/tests/auth_tests/test_models.py +++ b/tests/auth_tests/test_models.py @@ -345,6 +345,14 @@ class AnonymousUserTests(SimpleTestCase): def test_hash(self): self.assertEqual(hash(self.user), 1) + def test_int(self): + msg = ( + 'Cannot cast AnonymousUser to int. Are you trying to use it in ' + 'place of User?' + ) + with self.assertRaisesMessage(TypeError, msg): + int(self.user) + def test_delete(self): with self.assertRaisesMessage(NotImplementedError, self.no_repr_msg): self.user.delete()