Problem testing user is None when extending auth backend.

390 views
Skip to first unread message

graeme

unread,
Sep 28, 2017, 7:50:27 AM9/28/17
to Django users
In a custom authentication backend, I was getting this error with this (previous developer's!) code:
   if user.is_authenticated() and user.is_staff:
AttributeError: 'NoneType' object has no attribute 'is_authenticated'

The cause seemed clear, the parent classes method was run first with super and returned None when it failed to authenticate, so I tried to fix by testing whether user is None, but I still get this:

if (user is not None) and user.is_authenticated() and user.is_staff:
AttributeError: 'NoneType' object has no attribute 'is_authenticated'

I am probably missing something obvious, but if user is None, only (user is not None) will be evaluated there should be no error, if user is not None, I should not have a NoneType in the error.

Derek

unread,
Sep 28, 2017, 9:16:44 AM9/28/17
to Django users
Note that
user.is_authenticated()
has become
user.is_authenticated
in Django 1.10

Otherwise if user is really (or could really) be None, then try... except may be better:

try:
if user.is_authenticated() and user.is_staff:
do something
else:
do something else
except AttributeError as err:
 log.error('User not found:%s' % err)


graeme

unread,
Sep 28, 2017, 2:52:12 PM9/28/17
to Django users


On Thursday, September 28, 2017 at 2:16:44 PM UTC+1, Derek wrote:
Note that
user.is_authenticated()
has become
user.is_authenticated
in Django 1.10
 
Still on 1.8 in this case

Otherwise if user is really (or could really) be None, then try... except may be better:
 
Thanks, will try it. I still do not understand why checking for not None does not work as I expected.

Importing the code into the Django shell and calling authenticate() with an invalid username/password combination works as expected
Reply all
Reply to author
Forward
0 new messages