psycopg2.errors.UndefinedTable: relation "api_customuser" does not exist

I got this error when I try to run migrate. I tried to delete migration and makemigration and makemigrations <appname>, but not anything happened

$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, api, auth, authtoken, contenttypes, sessions
Running migrations:
  Applying admin.0001_initial...Traceback (most recent call last):
  File "D:\code\restfullapi\env\lib\site-packages\django\db\backends\utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedTable: relation "api_customuser" does not exist


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

Traceback (most recent call last):
  File "D:\code\restfullapi\goodreads\manage.py", line 22, in <module>
    main()
  File "D:\code\restfullapi\goodreads\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "D:\code\restfullapi\env\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line
    utility.execute()
  File "D:\code\restfullapi\env\lib\site-packages\django\core\management\__init__.py", line 440, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "D:\code\restfullapi\env\lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "D:\code\restfullapi\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    with self.db.wrap_database_errors:
  File "D:\code\restfullapi\env\lib\site-packages\django\db\utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "D:\code\restfullapi\env\lib\site-packages\django\db\backends\utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "api_customuser" does not exist

models.py

from django.db import models
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import AbstractUser, UserManager, AbstractBaseUser, BaseUserManager, PermissionsMixin


class CustomUserManager(BaseUserManager):
    def create_user(self, email, password=None, **extra_fields):
        if not email:
            raise ValueError("User must have an email")
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, email, password=None, **extra_fields):
        user = self.create_user(email, password=password, **extra_fields)
        user.is_active = True
        user.is_staff = True
        user.is_admin = True
        user.save(using=self._db)
        return user


class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=255, unique=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)

    objects = CustomUserManager()

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = []

serializers.py

from rest_framework import serializers
from .models import CustomUser


class UserCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = CustomUser
        fields = [
            'id',
            'email',
        ]

setting.py

AUTH_USER_MODEL = 'api.CustomUser'


REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
}


DJOSER = {
    'USER_CREATE_PASSWORD_RETYPE': True,
    'SET_PASSWORD_RETYPE': True,
    'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}',
    'USERNAME_RESET_CONFIRM_URL': 'username/reset/confirm/{uid}/{token}',
    'ACTIVATION_URL': 'activate/{uid}/{token}',
    # 'SEND_ACTIVATION_EMAIL': True,
    # 'SEND_CONFIRMATION_EMAIL': True,
    # 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True,
    # 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True,
    'LOGOUT_ON_PASSWORD_CHANGE': True,

    'SERIALIZERS': {
        'user_create': 'api.serializers.UserCreateSerializer',

        'user': 'djoser.serializers.UserSerializer',
        'current_user': 'djoser.serializers.UserSerializer',
        'user_delete': 'djoser.serializers.UserDeleteSerializer',
        
    },
}
```

If you delete a migration file for a migration that has already been applied, it can be difficult to get everything back in sync again. If that’s the situation, then the quick fix is to drop the database, recreate it and redo the initial migration.

Otherwise, there are a number of different problems that could create this issue, such as code in one of your files that is referring to this model that isn’t in a function or class, or possibly a circular import, or some other type of fundamental structural error.

Probably the first thing that I would try would be to create a new database and change your DATABASES setting to refer to it - and see if you can run migrate on it.

If you can, then your migrations are out-of-sync with the existing database.

If you can’t, then you have something structurally wrong with your code.

1 Like

Thank you so much, it really helpful for me!