User ID Unique Constraint Fails when Logging In

I am using Django Rest Framework to and trying to log a user in. I have customised the User Model and also have a Profile Model with a OnetoOne relation to the User Model.

Here are my Models

from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
from django.contrib.auth import get_user_model


# Create your models here.
class UserManager(BaseUserManager):
    def create_user(self, email, password=None):
        if not email:
            raise ValueError('Users must have an email address')

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

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

    def create_superuser(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
        )
        user.is_admin = True
        user.is_staff = True
        user.save(using=self._db)
        return user
    
class User(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    date_joined = models.DateTimeField(auto_now_add=True)
    last_login = models.DateTimeField(auto_now_add=True) 

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True
    
    def save(self, *args, **kwargs):
        super(User, self).save(*args, **kwargs)
        profile = Profile(user=self)
        profile.save()
        return self
    

class Profile(models.Model):
    user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
    first_name = models.CharField(max_length=100, blank=True)
    last_name = models.CharField(max_length=100, blank=True)
    friend_requests = models.ManyToManyField('Profile', related_name='requests')
    friends = models.ManyToManyField('Profile', related_name='friends_list')
    
    def __str__(self):
        return self.user.email

Now I am trying to log a User In with the following view:

@api_view(['POST',])
def login(request):
    user = auth.authenticate(
        username=request.data['email'], password=request.data['password'])
    
    if user:
        auth.login(request, user)
        return Response({'Status': 'Success', "Message": "You have successfully Logged In!"}, status=status.HTTP_200_OK)

    return Response({'Status': 'Failed', "Message": "Invalid Credentials!"}, status=status.HTTP_401_UNAUTHORIZED)

And it is giving me the following error:

Internal Server Error: /login/
Traceback (most recent call last):
  File "X:\Social Media API\env\Lib\site-packages\django\db\backends\utils.py", line 105, in _execute
    return self.cursor.execute(sql, params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "X:\Social Media API\env\Lib\site-packages\django\db\backends\sqlite3\base.py", line 329, in execute
    return super().execute(query, params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
sqlite3.IntegrityError: UNIQUE constraint failed: APIs_profile.user_id

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "X:\Social Media API\env\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "X:\Social Media API\env\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "X:\Social Media API\env\Lib\site-packages\django\views\decorators\csrf.py", line 65, in _view_wrapper
    return view_func(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "X:\Social Media API\env\Lib\site-packages\django\views\generic\base.py", line 104, in view
    return self.dispatch(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "X:\Social Media API\env\Lib\site-packages\rest_framework\views.py", line 509, in dispatch
    response = self.handle_exception(exc)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "X:\Social Media API\env\Lib\site-packages\rest_framework\views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "X:\Social Media API\env\Lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
    raise exc
  File "X:\Social Media API\env\Lib\site-packages\rest_framework\views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "X:\Social Media API\env\Lib\site-packages\rest_framework\decorators.py", line 50, in handler
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "X:\Social Media API\APIs\views.py", line 26, in login
    auth.login(request, user)
  File "X:\Social Media API\env\Lib\site-packages\django\contrib\auth\__init__.py", line 152, in login
    user_logged_in.send(sender=user.__class__, request=request, user=user)
  File "X:\Social Media API\env\Lib\site-packages\django\dispatch\dispatcher.py", line 189, in send
    response = receiver(signal=self, sender=sender, **named)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "X:\Social Media API\env\Lib\site-packages\django\contrib\auth\models.py", line 23, in update_last_login
    user.save(update_fields=["last_login"])
  File "X:\Social Media API\APIs\models.py", line 59, in save
    profile.save()
  File "X:\Social Media API\env\Lib\site-packages\django\db\models\base.py", line 822, in save
    self.save_base(
  File "X:\Social Media API\env\Lib\site-packages\django\db\models\base.py", line 909, in save_base
    updated = self._save_table(
              ^^^^^^^^^^^^^^^^^
  File "X:\Social Media API\env\Lib\site-packages\django\db\models\base.py", line 1071, in _save_table
    results = self._do_insert(
              ^^^^^^^^^^^^^^^^
  File "X:\Social Media API\env\Lib\site-packages\django\db\models\base.py", line 1112, in _do_insert
    return manager._insert(
           ^^^^^^^^^^^^^^^^
  File "X:\Social Media API\env\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "X:\Social Media API\env\Lib\site-packages\django\db\models\query.py", line 1847, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "X:\Social Media API\env\Lib\site-packages\django\db\models\sql\compiler.py", line 1823, in execute_sql
    cursor.execute(sql, params)
  File "X:\Social Media API\env\Lib\site-packages\django\db\backends\utils.py", line 122, in execute
    return super().execute(sql, params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "X:\Social Media API\env\Lib\site-packages\django\db\backends\utils.py", line 79, in execute
    return self._execute_with_wrappers(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "X:\Social Media API\env\Lib\site-packages\django\db\backends\utils.py", line 92, in _execute_with_wrappers
    return executor(sql, params, many, context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "X:\Social Media API\env\Lib\site-packages\django\db\backends\utils.py", line 100, in _execute
    with self.db.wrap_database_errors:
  File "X:\Social Media API\env\Lib\site-packages\django\db\utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "X:\Social Media API\env\Lib\site-packages\django\db\backends\utils.py", line 105, in _execute
    return self.cursor.execute(sql, params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "X:\Social Media API\env\Lib\site-packages\django\db\backends\sqlite3\base.py", line 329, in execute
    return super().execute(query, params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
django.db.utils.IntegrityError: UNIQUE constraint failed: APIs_profile.user_id

I have also written a custom authentication backend as follows:

from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend

class EmailBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        UserModel = get_user_model()
        try:
            user = UserModel.objects.get(email=username)
        except UserModel.DoesNotExist:
            return None
        else:
            if user.check_password(password):
                return user
        return None

Now I am not getting what’s the actual problem with this code. Can anyone help me out?

Here is the link to the GitHub Repo

Your save method of your User model is trying to create a new Profile every time it’s called. Each time you log in, Django is going to update the last_login field - this causes the User.save method to be called.