# psycopg2.errors.UndefinedTable: relation "api\_customuser" does not exist

**URL:** <https://forum.djangoproject.com/t/psycopg2-errors-undefinedtable-relation-api-customuser-does-not-exist/14498>\
**Category:** Using the ORM\
**Created:** [June 27, 2022, 9:31am UTC](https://forum.djangoproject.com/t/psycopg2-errors-undefinedtable-relation-api-customuser-does-not-exist/14498 "2022-06-27T09:31:48Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![kev26](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kev26/32/3647_2.png) [@kev26](https://forum.djangoproject.com/u/kev26)\
**Post date:** [June 27, 2022, 9:31am UTC](https://forum.djangoproject.com/t/psycopg2-errors-undefinedtable-relation-api-customuser-does-not-exist/14498/1 "2022-06-27T09:31:48Z")

</div>

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

```plaintext
$ 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

```python
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

```python
from rest_framework import serializers
from .models import CustomUser

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

```

setting.py

````python
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',
        
    },
}
```
````

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [June 27, 2022, 9:53am UTC](https://forum.djangoproject.com/t/psycopg2-errors-undefinedtable-relation-api-customuser-does-not-exist/14498/2 "2022-06-27T09:53:21Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![kev26](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kev26/32/3647_2.png) [@kev26](https://forum.djangoproject.com/u/kev26)\
**Post date:** [June 27, 2022, 9:56am UTC](https://forum.djangoproject.com/t/psycopg2-errors-undefinedtable-relation-api-customuser-does-not-exist/14498/3 "2022-06-27T09:56:04Z")

</div>

Thank you so much, it really helpful for me!
