Skip to content Skip to sidebar Skip to footer

Django's Admin Does Not Login After Custom Authentication

The custom authentication I wrote follows the instructions from the docs. I am able to register, login, and logout the user, no problem there. Then, when I create a superuser pyt

Solution 1:

I think the problem is in your EmailAuthBackend. If you add some printing/logging to the backend, you'll find that the login form calls the authenticate method with username and password. This means that email is None, and therefore the user = User.objects.get(email = email) lookup fails.

In your case, the regular ModelBackend will work fine for you, because you have USERNAME_FIELD = 'email'. If you remove AUTHENTICATION_BACKENDS from your settings then the login should work. You can then remove your EmailAuthBackend.

If you wanted to log in users with their cell number and password (and cell_number was not the USERNAME_FIELD, then you would need a custom authentication backend. You would also need a custom authentication form that called authenticate(cell_number=cell_number, password=password). Another example of a custom authentication backed is RemoteUserBackend, which logs in the user based on an environment variable set by the server.

Solution 2:

Had the same issue. Instead of password=None, I changed it to password only. And passed 'password=password' , together with 'username=username' as you can see below:

classMyAccountManager(BaseUserManager):
    defcreate_user(self, email, username, password):
        ifnot email:
            raise ValueError('Please add an email address')
        ifnot username:
            raise ValueError('Please add an username')

        user = self.model(email=self.normalize_email(
            email), username=username, password=password)

        user.set_password(password)
        user.save(using=self._db)
        return user

    defcreate_superuser(self, email, username, password):
        user = self.create_user(email=self.normalize_email(
            email), username=username, password=password)

And as Denis has already said above, make sure to add AUTH_USER_MODEL = 'accounts.User' to settings.py

Post a Comment for "Django's Admin Does Not Login After Custom Authentication"