2

I am trying to create an authentication token for my model called Person, but the Token table asks me for a user_id as a foreign key, is there any way I can create tokens with a different User model?

This is my Person model:

class Person(AbstractBaseUser):
 first_name = models.CharField('Nombre', max_length = 100)
 last_name = models.CharField('Apellido', max_length = 100)
 username = models.CharField('Username', max_length = 50)
 nickname = models.CharField('Nickname', max_length = 50, null = True)
 gener = models.IntegerField('Genero')
 phone = models.CharField('Teléfono', max_length = 13, null = True)
 birtday = models.DateField('Cumpleaños', auto_now=False, auto_now_add=False, null = True)
 address_id = models.IntegerField('Dirección', null = True)
 address_birtday_id = models.IntegerField('Lugar de Nacimiento', null = True)
 email = models.EmailField('Correo', max_length=254)
 password = models.CharField('Password', max_length = 700)
 photo = models.CharField('Foto', max_length=254, null = True)
 about_me = models.CharField('Biografía', max_length = 1000, null = True)
 active = models.IntegerField('Activo')
 connected = models.IntegerField('Conectado')
 person_type_id = models.IntegerField('Tipo', null = True)
 created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True)
 updated_at = models.DateTimeField(auto_now=True, null=True, blank=True)

 USERNAME_FIELD = 'username'

 def __str__(self):
     return '{0},{1}'.format(self.last_name, self.first_name)

This is my view:

class LoginPersonAPI(APIView):
 def post(self, request):
    serializer = LoginPersonSerializer(data = request.data)
    if serializer.is_valid():
        person = Person.objects.filter(username=serializer.validated_data['username'])
        token = Token.objects.get_or_create(key = person[0].id)
        if token:
            return Response(token[0])
        return Response(person[0].id, status = status.HTTP_201_CREATED)
    else:
        return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)

This is my serializer:

class LoginPersonSerializer(serializers.Serializer):
 username = serializers.CharField()
 password = serializers.CharField()

 def login(self, validate_data):
    instance = Person
    instance.username = validate_data.get("username")
    instance.password = validate_data.get("password")
    instance.find()
    return instance

and this is the error

null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (3, 2020-06-27 19:39:53.283721+00, null).

  • Have you tried to use AbstractUser instead of AbstractBasedUSer? And set the Person model as the authentication one instead of the User in your settings.py? – Elias Prado Jun 09 '21 at 14:48

0 Answers0