Fixed #26988 -- Improved/clarified User.is_authenticated/anonymous compatibility.

Thanks marktranchant for the report and review.
This commit is contained in:
Tim Graham 2016-08-02 09:32:00 -04:00
parent d95c669c29
commit 54afa960d1
4 changed files with 33 additions and 0 deletions

View File

@ -110,6 +110,12 @@ class CallableBool:
def __repr__(self): def __repr__(self):
return 'CallableBool(%r)' % self.value return 'CallableBool(%r)' % self.value
def __eq__(self, other):
return self.value == other
def __ne__(self, other):
return self.value != other
CallableFalse = CallableBool(False) CallableFalse = CallableBool(False)
CallableTrue = CallableBool(True) CallableTrue = CallableBool(True)

View File

@ -11,3 +11,6 @@ Bugfixes
* Fixed a crash in MySQL connections where ``SELECT @@SQL_AUTO_IS_NULL`` * Fixed a crash in MySQL connections where ``SELECT @@SQL_AUTO_IS_NULL``
doesn't return a result (:ticket:`26991`). doesn't return a result (:ticket:`26991`).
* Allowed ``User.is_authenticated`` and ``User.is_anonymous`` properties to be
compared using ``==`` and ``!=`` (:ticket:`26988`).

View File

@ -1061,6 +1061,14 @@ method, e.g.::
If you override these methods in a custom user model, you must change them to If you override these methods in a custom user model, you must change them to
properties or attributes. properties or attributes.
Django uses a ``CallableBool`` object to allow these attributes to work as both
a property and a method. Thus, until the deprecation period ends, you cannot
compare these properties using the ``is`` operator. That is, the following
won't work::
if request.user.is_authenticated is True:
...
Custom manager classes available through ``prefetch_related`` must define a ``_apply_rel_filters()`` method Custom manager classes available through ``prefetch_related`` must define a ``_apply_rel_filters()`` method
----------------------------------------------------------------------------------------------------------- -----------------------------------------------------------------------------------------------------------

View File

@ -0,0 +1,16 @@
from django.test import SimpleTestCase
from django.utils.deprecation import CallableFalse, CallableTrue
class TestCallableBool(SimpleTestCase):
def test_true(self):
self.assertTrue(CallableTrue)
self.assertEqual(CallableTrue, True)
self.assertFalse(CallableTrue != True) # noqa: E712
self.assertNotEqual(CallableTrue, False)
def test_false(self):
self.assertFalse(CallableFalse)
self.assertEqual(CallableFalse, False)
self.assertFalse(CallableFalse != False) # noqa: E712
self.assertNotEqual(CallableFalse, True)