diff --git a/django/contrib/auth/models.py b/django/contrib/auth/models.py index 304095488d..737d6d3aea 100644 --- a/django/contrib/auth/models.py +++ b/django/contrib/auth/models.py @@ -509,3 +509,6 @@ class AnonymousUser(object): def is_authenticated(self): return False + + def get_username(self): + return self.username diff --git a/django/contrib/auth/tests/test_basic.py b/django/contrib/auth/tests/test_basic.py index 9cf7eedca4..fed94db82f 100644 --- a/django/contrib/auth/tests/test_basic.py +++ b/django/contrib/auth/tests/test_basic.py @@ -41,6 +41,9 @@ class BasicTestCase(TestCase): u.set_password(None) self.assertFalse(u.has_usable_password()) + # Check username getter + self.assertEqual(u.get_username(), 'testuser') + # Check authentication/permissions self.assertTrue(u.is_authenticated()) self.assertFalse(u.is_staff) @@ -66,6 +69,8 @@ class BasicTestCase(TestCase): "Check the properties of the anonymous user" a = AnonymousUser() self.assertEqual(a.pk, None) + self.assertEqual(a.username, '') + self.assertEqual(a.get_username(), '') self.assertFalse(a.is_authenticated()) self.assertFalse(a.is_staff) self.assertFalse(a.is_active) diff --git a/docs/ref/contrib/auth.txt b/docs/ref/contrib/auth.txt index 3c96fc835a..1d09359e50 100644 --- a/docs/ref/contrib/auth.txt +++ b/docs/ref/contrib/auth.txt @@ -269,6 +269,10 @@ Anonymous users these differences: * :ref:`id ` is always ``None``. + * :attr:`~django.contrib.auth.models.User.username` is always the empty + string. + * :meth:`~django.contrib.auth.models.User.get_username()` always returns + the empty string. * :attr:`~django.contrib.auth.models.User.is_staff` and :attr:`~django.contrib.auth.models.User.is_superuser` are always ``False``. @@ -285,6 +289,11 @@ Anonymous users :meth:`~django.db.models.Model.save` and :meth:`~django.db.models.Model.delete()` raise :exc:`NotImplementedError`. + .. versionadded:: 1.8 + + ``AnonymousUser.get_username()`` has been added to + better mirror :class:`django.contrib.auth.models.User`. + In practice, you probably won't need to use :class:`~django.contrib.auth.models.AnonymousUser` objects on your own, but they're used by Web requests, as explained in the next section.