Django Authorization Error

I really miss what is happening here. Django 1.3.

Symptom: Authentication is just overloaded. I reduced the problem to this:

./manage.py shell Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>>from django.contrib.auth.models import User >>> users = User.objects.all() >>> users [<User: jal>] >>> users[0].set_password('whatever'); >>> users[0].save() >>> user = auth.authenticate(username="jal", password="whatever") >>> print user None 

I am in difficulty.

Edit:

 >>> from django.contrib.auth.models import User >>> user = User.objects.get(username="jal") >>> print user jal >>> user.check_password('whatever') False 

I am using django.contrib.auth.backends.ModelBackend.

Edit two:

 >>> print user jal >>> print user.is_active True 

Edit three:

Alasdair is right - thanks.

 >>> users = User.objects.all() >>> user = users[0] >>> user.set_password('whatever') >>> user.save() >>> u2 = auth.authenticate(username="jal", password="whatever") >>> print u2 jal 

This still leaves a secret as to why it has been violated for actual access to the Django admin GUI, and that is why I led this road in the first place. This gives me “Please enter a valid username and password. Please note that both fields are case sensitive” is the password correct.

+4
source share
2 answers

You are having this problem because Django querysets are lazy . Each time you access users[0] , Django returns another object.

To demonstrate this, try the following:

 >>> users = User.objects.all() >>> print id(users[0]) 58753692 >>> print id(users[0]) 58753111 

You can see that the identifier of the object is different each time. The object you save is not the object on which you set the password. The new password was not saved in the database, so authentication failed.

To get around this, you can assign users [0] to a variable or list() to force a query to be evaluated.

 # Assign users[0] to a variable. users = User.objects.all() user = users[0] user.set_password('whatever') user.save() # Force the queryset to be evaluated by using list() users = list(User.objects.all()) users[0].set_password('whatever') users[0].save() 

Change This suggestion was not a problem here, but could help someone else.

what is the value of AUTHENTICATION_BACKENDS in your settings file. You should not define it in your settings.py , since by default it will be:

 AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) 

If you set it up for something else, this can cause problems.

+4
source

Have you verified that usage is active? (User.is_active)

An inactive user does not have permission and cannot log in (unless you configure something)

+1
source

Source: https://habr.com/ru/post/1395472/


All Articles