Django authenticate dont work for Custom User

In my django-rest project , I am trying to make a login autentication using knox

But in my views , even when the user exists and I provide the username and password correctly, serializer.is_valid(raise_exception=True) always returns False

I check the validation method for the AuthKnoxSerializer

class AuthTokenSerializer(serializers.Serializer):
   def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')

        if username and password:
            user = authenticate(request=self.context.get('request'),
                                username=username, password=password)

When i check in django shell if autenticate is working properly

in django shell

>>>from django.contrib.auth import authenticate
>>>from django.contrib.auth import get_user_model
<MyUser: CIEMSA>
>>>print(authenticate(username="CIEMSA", password="225236Cm."))



        # 'rest_framework.authentication.BasicAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
    'USER_SERIALIZER': 'api.serializers.UserSerializer'

AUTH_USER_MODEL = "api.MyUser"

from rest_framework.authtoken.serializers import AuthTokenSerializer
from knox.views import LoginView as KnoxLoginView

class LoginAPI(KnoxLoginView):
    permission_classes = (permissions.AllowAny,)

    def post(self, request, format=None):
        serializer = AuthTokenSerializer(
        user = serializer.validated_data['user']
        login(request, user)
        return super(LoginAPI, self).post(request, format=None)


from django.db import models as m
from django.contrib.auth import get_user_model
from django.dispatch import receiver
from django.contrib.auth.models import AbstractUser

class Company(m.Model):
    name = m.CharField(max_length=100)
    phone_number = m.CharField(max_length=20)
    provider = m.CharField(max_length=15,
    account_sid = m.CharField(max_length=512, null=True)
    auth_token = m.TextField(max_length=512, null=True)

    def __str__(self):
        return f'({}) {}, {self.phone_number}'

class MyUser(AbstractUser):
    company  = m.OneToOneField(Company, null=True , on_delete=m.CASCADE)

@receiver(post_save, sender=Company)
def list_create(sender, instance=None, created=False, **kwargs):
    if created:
        get_user_model().objects.create(company=instance,, password=instance.password)

Any ideas why is not working?

You're not correctly setting the password, try it like this:

@receiver(post_save, sender=Company)
def list_create(sender, instance=None, created=False, **kwargs):
    if created:
        user = get_user_model().objects.create(company=instance,

Now my question is, where does instance.password come from, as you shouldn't store passwords as plain text field in your database.

Back to Top