微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

“django.db.utils.ProgrammingError: 关系“account_account”不存在”同时使用 Oauth for API 和自定义用户模型

如何解决“django.db.utils.ProgrammingError: 关系“account_account”不存在”同时使用 Oauth for API 和自定义用户模型

我正在尝试使用 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,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,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,many,context)
  File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\python39\lib\site-packages\django\db\backends\utils.py",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",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,password):
        # call the function create user to create a super user
        user = self.create_user(
            email=self.normalize_email(email),password=password,)
        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'
]

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

解决方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。