I have the following code snippet:

user = User(username='h@h.com',email='h@h.com')
user.set_password('pass')
user.save()
u = authenticate(username='h@h.com', password='pass') #this always returns None!!!

The problem is, u is always None. I've followed code samples on other stack overflow posts and have narrowed it down to the above lines.

Any ideas as to what might be happening?

有帮助吗?

解决方案

Put something like this in your settings

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

or if you are using userena for your accounts

#Authentication backends
AUTHENTICATION_BACKENDS = (
    'userena.backends.UserenaAuthenticationBackend',
    'guardian.backends.ObjectPermissionBackend',
    'django.contrib.auth.backends.ModelBackend',
)

其他提示

Interestingly enough, check_password returns True in the following:

eml = "4@a.com"
pw = "pass"
uname = 'w2'
user = User.objects.create_user(uname,eml,pw)
user.save()
log.debug("Password check passes?")
log.debug(user.check_password(pw)) # Logs True!!!
user = authenticate(username=uname, password=pw)

Why don't you create a user like this:

user = User.objects.create_user( username="whatever", email="whatever@some.com", password="password")
user = authenticate( username="whatever",password="password")

In settings.py, add

AUTH_USER_MODEL = your custom user class

e.g if django app name is office and custom user class is Account then

AUTH_USER_MODEL = 'office.Account'

set_password is a misleading method, it doesn't save the password on the user table. You need to call user.save() in order for it to work on your flow

You have to check whether user is active? If not, you only set active for user in admin panel, or set when creating user by adding the following line to user model:

is_active = models.BooleanField(default=True)

Also check that you have the right username/password combo. sometimes the one that is created from the createsuperuser command is different than a username you would typically use.

As most of them suggested if we create the user's using User.objects.create_user(**validated_data) this will hash the raw password and store the hashed password. In-case if you you are using User model serializers to validate and create users, it is required to override the serializer method like this

class UserSerializers(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = "__all__"

    # this is the method responsible for insertion of data with hashed password
    def create(self, validated_data):
        return User.objects.create_user(**validated_data)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top