I want to log a user in with the following code:
try:
user = User.objects.get(username = username)
print "user found"
if user.password == password and user.is_active:
print "user: " + str(user)
try:
print "test1"
login(request, user)
print "test2"
except:
print "error"
import sys
print "--> " + str(sys.exc_info()[0])
raise
user_is_valid = True
print "hell yeah!!"
except:
user = None
print "failed"
What gives the following console output when logging in with a active user:
user found
user: testuser@email.com
test1
error
--> <type 'exceptions.AttributeError'>
failed
The usernames are email adresses but I see no problem with that. The user is active and as you can see is the user object not None. Why is the login method throwing the bad attribute exception and how can I fix this?
Why are you doing any of this? First of all, you shouldn’t be catching the exception only to re-raise it. Running with DEBUG on, Django provides you with an excellent error page which would have shown you the actual error and the code that raises it – in particular, you would have seen which attribute is being accessed.
Most likely, the error is that you haven’t called
authenticateon the user, which as well as checking the password also adds an attribute recording which authentication backend authenticated that user. The documentation on how to log a user in is quite clear that you need to call this – note the box stating ‘callingauthenticatefirst’.The third thing you should definitely not be doing is checking a password as text – Django stores them as hashes, so you need to compare the hashed value. Again,
authenticatewill take care of this for you.