I am trying to create a API with OAuth 2 Authentication. I have created custom user models called Accounts. When I am running the command "py manage.py migrate" it is throwing me the below error.

E:\Django\api\app>py manage.py migrate                          
Operations to perform:
  Apply all migrations: account, admin, app_v2, auth, contenttypes, oauth2_provider, sessions, social_django
Running migrations:
  Applying oauth2_provider.0001_initial...Traceback (most recent call last):
  File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedTable: relation "account_account" does not exist


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

Traceback (most recent call last):
  File "E:\Django\api\app\manage.py", line 22, in <module>
    main()
  File "E:\Django\api\app\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line     
    utility.execute()
  File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle
    post_migrate_state = executor.migrate(
  File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 230, in apply_migration
    migration_recorded = True
  File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 118, in __exit__
    self.execute(sql)
  File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 145, in execute
    cursor.execute(sql, params)
  File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 98, in execute
    return super().execute(sql, params)
  File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "account_account" does not exist

Packages Used for Authentication.

pip install django-oauth-toolkit djangorestframework

Models.py for Accounts

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

from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token

# These Class is used to create a normal user and a super user
class MyAccountManager(BaseUserManager):

    # Function to create user
    def create_user(self, email, username, password=None):
        if not email:
            raise ValueError("Users must have an email address. ")
        if not username:
            raise ValueError("Users must have a username. ")
        user = self.model(
            email=self.normalize_email(email),
            username=username,
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    # Function to create a Super User
    # we are not mentioning password as None for super user
    def create_superuser(self, email, username, password):
        # call the function create user to create a super user
        user = self.create_user(
            email=self.normalize_email(email),
            password=password,
            username=username,
        )
        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True
        user.save(using=self._db)
        return user

# represents the table Account in Postgress
class Account(AbstractBaseUser, PermissionsMixin):
    password = models.CharField(max_length=128)
    last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
    is_superuser = models.BooleanField(default=False)
    username = models.CharField(max_length=150, unique=True)
    first_name = models.CharField(max_length=150)
    last_name = models.CharField(max_length=150)
    email = models.CharField(verbose_name='email', max_length=254, unique=True)
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)

    #unique field to identify our user model
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    # this helps the model to understand that we are using MyAccountManager to create accounts(Users)
    objects = MyAccountManager()

    def __str__(self):
        return self.email

    # For checking permissions. To keep it simple all admin have ALL permissions
    def has_perm(self, perm, obj=None):
        return self.is_admin

    # Does this user have permission to view this app? (ALWAYS YES FOR SIMPLICITY)
    def has_module_perms(self, app_label):
        return True

I have also added this lines in Settings.py

AUTH_USER_MODEL = "account.Account"
AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.AllowAllUsersModelBackend',
    'account.backends.CaseInsensitiveModelBackend'
]

I don't have any idea why it is throwing this error. please help me!!!

1

There are 1 answers

2
MR.NECRO On

This error also occurs when you have misplaced something in database files either you have changed the database,so in order to fix this error all you need to do is just go to your root project and then remove pycache and migrations folder from each apps and do all the migrations & migrates explicitly like for an example "python manage.py makemigrations app name" and also the same way for migrate "python manage.py migrate app name" and just restart the server your error would have been gone now :)