# Can't login in django admin using custom user

**URL:** <https://forum.djangoproject.com/t/cant-login-in-django-admin-using-custom-user/25873>\
**Category:** The Admin\
**Created:** [December 4, 2023, 8:25pm UTC](https://forum.djangoproject.com/t/cant-login-in-django-admin-using-custom-user/25873 "2023-12-04T20:25:34Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![DanielSantos](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/danielsantos/32/17547_2.png) [@DanielSantos](https://forum.djangoproject.com/u/DanielSantos)\
**Post date:** [December 4, 2023, 8:25pm UTC](https://forum.djangoproject.com/t/cant-login-in-django-admin-using-custom-user/25873/1 "2023-12-04T20:25:34Z")

</div>

I create a custom model for User.  
I can create a superuser using command line and its created successfully.

But when I try to login in django admin it does not redirect to the django admin itself.

I already verified that it is authenticating properly.

Here is the **backend** authentication created

```auto
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

User = get_user_model()

class AuthBackend(ModelBackend):
    supports_object_permissions = True
    supports_anonymous_user = False
    supports_inactive_user = False

    def get_user(self, nif):
        try:
            return User.objects.get(nif=nif)
        except User.DoesNotExist:
            return None

    def authenticate(self, request, username=None, password=None, **kwargs):
        print('inside custom auth')
        try:
            user = User.objects.get(
                Q(nif=username))
            print(user)
        except User.DoesNotExist:
            print('teste')
            return None

        if user.check_password(password):
            print('ok', user, password, **kwargs)
            print(self.user_can_authenticate(user))
            return user
        else:
            print('nok', user, password)
            return None

```

My app is on **apps/usuarios**.

Here is my configuration on **settings** :

```auto

DEBUG = True

ALLOWED_HOSTS = []

AUTH_USER_MODEL = "usuarios.User"

AUTHENTICATION_BACKENDS = [
    #"django.contrib.auth.backends.ModelBackend",
    "apps.usuarios.backend.AuthBackend",
]

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'apps.usuarios.apps.UsuariosConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'setup.urls'

```

I think it is a problem with redirection but I can’t figured what is causing this.  
What I am missing?

In the authentication method I put a debug to show if the user was authenticate properly and it is working, it gives no error on the screen.  
I also verified in shell that the custom super user created is with is\_staff True and is\_superuser True and is\_active True.

To debug if it was passing through the **authenticate method** on the **backends** correctly, I did this:

I created a user with NIF 1234567 and password 0000

If I try to login correctly the page shows no error but do not redirect to django admin and the terminal shows this:

> inside custom auth
> 
> 1234567
> 
> ok 1234567 0000
> 
> True
> 
> [03/Dec/2023 20:24:21] “POST /admin/login/?next=/admin/ HTTP/1.1” 302 0
> 
> [03/Dec/2023 20:24:21] “GET /admin/ HTTP/1.1” 302 0
> 
> [03/Dec/2023 20:24:21] “GET /admin/login/?next=/admin/ HTTP/1.1” 200 4207

If I try with an invalid nif and password the page shows the error correctly and here is the terminal:

> inside custom auth
> 
> 1234567
> 
> nok 1234567 1111
> 
> [03/Dec/2023 20:26:07] “POST /admin/login/?next=/admin/ HTTP/1.1” 200 4392

---

<div class="post-metadata">

**Author:** ![leandrodesouzadev](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/leandrodesouzadev/32/8981_2.png) [@leandrodesouzadev](https://forum.djangoproject.com/u/leandrodesouzadev)\
**Post date:** [December 4, 2023, 8:40pm UTC](https://forum.djangoproject.com/t/cant-login-in-django-admin-using-custom-user/25873/2 "2023-12-04T20:40:06Z")

</div>

Hey there!  
I would double check if the user is actually marked with is\_staff, even though you said it’s checked.  
Maybe the best place would be here:

> [@DanielSantos](#):
>
> ```auto
> print('inside custom auth')
> try:
> user = User.objects.get(
> Q(nif=username))
> print(user) ## <---
> 
> ```

---

<div class="post-metadata">

**Author:** ![DanielSantos](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/danielsantos/32/17547_2.png) [@DanielSantos](https://forum.djangoproject.com/u/DanielSantos)\
**Post date:** [December 4, 2023, 8:58pm UTC](https://forum.djangoproject.com/t/cant-login-in-django-admin-using-custom-user/25873/3 "2023-12-04T20:58:23Z")

</div>

Thanks for the repply. I tested and these 3 fields is True:  
is\_active  
is\_staff  
is\_superuser

 ![image](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/3X/5/a/5a7951136cb2af4b1160a7f25ebfe134e34cdf30.png)

---

<div class="post-metadata">

**Author:** ![antoinehumbert](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/antoinehumbert/32/14851_2.png) [@antoinehumbert](https://forum.djangoproject.com/u/antoinehumbert)\
**Post date:** [December 4, 2023, 9:21pm UTC](https://forum.djangoproject.com/t/cant-login-in-django-admin-using-custom-user/25873/4 "2023-12-04T21:21:04Z")

</div>

Hi, is the `nif` field the primary key of your user model ?

As stated in documentation (see [Customizing authentication in Django | Django documentation | Django](https://docs.djangoproject.com/en/4.2/topics/auth/customizing/#writing-an-authentication-backend)) the parameter of the `get_user` method “has to be the primary key of your user object”.

Here, I think that after login, your user cannot be retrieved from pk saved in session as `get_user` returns `None` because it tried to match the `nif` with a value corresponding to primary key.

I think you do not need to override `get_user`.

---

<div class="post-metadata">

**Author:** ![DanielSantos](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/danielsantos/32/17547_2.png) [@DanielSantos](https://forum.djangoproject.com/u/DanielSantos)\
**Post date:** [December 5, 2023, 1:26am UTC](https://forum.djangoproject.com/t/cant-login-in-django-admin-using-custom-user/25873/5 "2023-12-05T01:26:25Z")

</div>

You found exactly what I was missing, I changed my model putting the primary\_key on the nif.

Nif field before:

```auto
nif_validator = RegexValidator(
        regex='^[1-9]{1}[0-9]{5,6}$',
        message="Invalid NIF (Valid pattern: 1234567",
    )
nif = models.CharField(
        _("NIF"),
        max_length=7,
        unique=True,
        validators=[nif_validator],
        blank=False,
        null=False,
        error_messages={
            "unique": _("NIF already registered in the system"),
            "validators": _("Invalid NIF (Valid pattern: 1234567"),
        },
    )

```

NIF Field after:

```auto
nif_validator = RegexValidator(
        regex='^[1-9]{1}[0-9]{5,6}$',
        message="Invalid NIF (Valid pattern: 1234567",
    )
nif = models.CharField(
        _("NIF"),
        max_length=7,
        primary_key=True, # <---- Added line to resolve login issue in Django Admin
        unique=True,
        validators=[nif_validator],
        blank=False,
        null=False,
        error_messages={
            "unique": _("NIF already registered in the system"),
            "validators": _("Invalid NIF (Valid pattern: 1234567"),
        },
    )

```
