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(

        return user

    def create_superuser(self, email, password=None):
        user = self.create_user(
        user.is_admin = True
        user.is_staff = True
        return user
class User(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
    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'

    def __str__(self):

    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)
        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):

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

def login(request):
    user = auth.authenticate(['email'],['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\", line 105, in _execute
    return self.cursor.execute(sql, params)
  File "X:\Social Media API\env\Lib\site-packages\django\db\backends\sqlite3\", 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\", line 55, in inner
    response = get_response(request)
  File "X:\Social Media API\env\Lib\site-packages\django\core\handlers\", 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\", line 65, in _view_wrapper
    return view_func(request, *args, **kwargs)
  File "X:\Social Media API\env\Lib\site-packages\django\views\generic\", line 104, in view
    return self.dispatch(request, *args, **kwargs)
  File "X:\Social Media API\env\Lib\site-packages\rest_framework\", line 509, in dispatch
    response = self.handle_exception(exc)
  File "X:\Social Media API\env\Lib\site-packages\rest_framework\", line 469, in handle_exception
  File "X:\Social Media API\env\Lib\site-packages\rest_framework\", line 480, in raise_uncaught_exception
    raise exc
  File "X:\Social Media API\env\Lib\site-packages\rest_framework\", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "X:\Social Media API\env\Lib\site-packages\rest_framework\", line 50, in handler
    return func(*args, **kwargs)
  File "X:\Social Media API\APIs\", line 26, in login
    auth.login(request, user)
  File "X:\Social Media API\env\Lib\site-packages\django\contrib\auth\", 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\", line 189, in send
    response = receiver(signal=self, sender=sender, **named)
  File "X:\Social Media API\env\Lib\site-packages\django\contrib\auth\", line 23, in update_last_login["last_login"])
  File "X:\Social Media API\APIs\", line 59, in save
  File "X:\Social Media API\env\Lib\site-packages\django\db\models\", line 822, in save
  File "X:\Social Media API\env\Lib\site-packages\django\db\models\", line 909, in save_base
    updated = self._save_table(
  File "X:\Social Media API\env\Lib\site-packages\django\db\models\", line 1071, in _save_table
    results = self._do_insert(
  File "X:\Social Media API\env\Lib\site-packages\django\db\models\", line 1112, in _do_insert
    return manager._insert(
  File "X:\Social Media API\env\Lib\site-packages\django\db\models\", 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\", 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\", line 1823, in execute_sql
    cursor.execute(sql, params)
  File "X:\Social Media API\env\Lib\site-packages\django\db\backends\", line 122, in execute
    return super().execute(sql, params)
  File "X:\Social Media API\env\Lib\site-packages\django\db\backends\", line 79, in execute
    return self._execute_with_wrappers(
  File "X:\Social Media API\env\Lib\site-packages\django\db\backends\", line 92, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "X:\Social Media API\env\Lib\site-packages\django\db\backends\", line 100, in _execute
    with self.db.wrap_database_errors:
  File "X:\Social Media API\env\Lib\site-packages\django\db\", 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\", line 105, in _execute
    return self.cursor.execute(sql, params)
  File "X:\Social Media API\env\Lib\site-packages\django\db\backends\sqlite3\", 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()
            user = UserModel.objects.get(email=username)
        except UserModel.DoesNotExist:
            return None
            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 method to be called.