Ignore `is_active` filed for custom user model

661 Views Asked by At

I'm trying to make custom user model, when instead of few boolean columns, I will manage user permissions based on one status filed:

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _


class MyUser(AbstractUser):
    username = None
    is_staff = None
    is_superuser = None
    is_active = None
    email = models.EmailField(_('email address'), unique=True)
    status = models.PositiveSmallIntegerField(default=0)

In settings.py file added:

AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.AllowAllUsersModelBackend']

Then, when trying to login, getting error: This account is inactive.

How to ignore is_active filed for my custom user model ?

2

There are 2 best solutions below

5
willeM_ Van Onsem On BEST ANSWER

You can replace is_active with a property, so:

class MyUser(AbstractUser):
    # …
    # no is_active field
    # …
    @property
    def is_active(self):
        return self.status > 0
0
Amin On

As docs says in https://docs.djangoproject.com/en/3.2/ref/contrib/auth/#django.contrib.auth.models.User.has_perm:

You can use AllowAllUsersModelBackend or AllowAllUsersRemoteUserBackend if you want to allow inactive users to login. In this case, you’ll also want to customize the AuthenticationForm used by the LoginView as it rejects inactive users. Be aware that the permission-checking methods such as has_perm() and the authentication in the Django admin all return False for inactive users.

So you have to override has_perm() method to ignore is_active()