0

我正在尝试使用 OAuth 2 身份验证创建 API。我创建了名为 Accounts 的自定义用户模型。当我运行命令“ py manage.py migrate ”时,它向我抛出了以下错误。

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

用于身份验证的包。

pip install django-oauth-toolkit djangorestframework

用于帐户的 Models.py

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

我还在 Settings.py 中添加了这一行

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

我不知道它为什么会抛出这个错误。请帮我!!!

4

1 回答 1

1

当您在数据库文件中放错了某些内容或者您更改了数据库时,也会发生此错误,因此为了修复此错误,您只需转到您的根项目,然后从每个应用程序中删除pycache和迁移文件夹并执行所有迁移和迁移都明确地像示例“python manage.py makemigrations app name”以及迁移“python manage.py migrate app name”的方式相同,只需重新启动服务器,您的错误就会消失了:)

于 2021-07-31T09:11:53.097 回答