Django:数据库配置不当,请提供引擎值。 (多个数据库)

Django: DATABASES IMPROPERLY CONFIGURED, Please supply engine value. (Multiple databases)

大家好,我想在我的 django 项目中使用 2 个 postgres 数据库,一个用于保存用户数据,另一个用于保存其他内容,但是当我尝试 运行 createsuperuser 但我能够 运行 makemigrationsmigrate --database=users_db 以及其他数据库也是如此。

    raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.

在 django 文档中,他们提到可以将 default 字典留空。 If the concept of a default database doesn’t make sense in the context of your project, you need to be careful to always specify the database that you want to use. Django requires that a default database entry be defined, but the parameters dictionary can be left blank if it will not be used. To do this, you must set up DATABASE_ROUTERS for all of your apps’ models, including those in any contrib and third-party apps you’re using, so that no queries are routed to the default database.

这是settings.py

DATABASES = {
'default': {},

'users_db': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'users_db',
    'USER': 'postgres',
    'PASSWORD': 'Trial_user123',
    'HOST':'127.0.0.1',
    'PORT':'5432',
},

'content_db': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'content_II',
    'USER': 'postgres',
    'PASSWORD': 'Trial_user123',
    'HOST':'127.0.0.1',
    'PORT':'5432',
},
}

DATABASE_ROUTERS = ['personal.routers.db_routers.AuthRouter', 'personal.routers.db_routers.PersonalDBRouter', ]

这是db_routers.py

class AuthRouter:
    route_app_labels = {'sessions', 'auth', 'contenttypes', 'admin', 'accounts'}

    def db_for_read(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return 'users_db'
        return None

    def db_for_read(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return 'users_db'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        if (
            obj1._meta.app_label in self.route_app_labels or
            obj2._meta.app_label in self.route_app_labels
        ):
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if app_label in self.route_app_labels:
            return 'users_db'
        return None
    

class PersonalDBRouter:
    route_app_labels = {'actions', 'blog', 'token_blacklist', 'taggit', 'django_celery_beat', 'django_celery_results',}

    def db_for_read(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return 'content_db'
        return None

    def db_for_read(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return 'content_db'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        if (
            obj1._meta.app_label in self.route_app_labels or
            obj2._meta.app_label in self.route_app_labels
        ):
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if app_label in self.route_app_labels:
            return 'content_db'
        return None

这是客户经理,当我尝试 运行 createsuperuser 时,它在 create_user 保存的行中显示错误。

class MyAccountManager(BaseUserManager):
    def create_user(self, email, username, first_name, last_name, password=None):
        if not email:
            raise ValueError('Users must have an email address')
        if not username:
            raise ValueError('Users must have a username')
        if not first_name:
            raise ValueError('Users must have a First Name') # check later

        user = self.model(
            email=self.normalize_email(email),
            username=username,
            first_name=first_name,
            last_name=last_name,
        )

        user.set_password(password)
        user.save(using="users_db")
        return user

    def create_superuser(self, email, username, first_name, last_name, password):
        user = self.create_user(
            email=self.normalize_email(email),
            password=password,
            username=username,
            first_name=first_name,
            last_name=last_name,
        )
        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True
        user.save(using=self._db)
        return user

我不明白是什么导致了这个错误,因为我已经提供了引擎值但找不到错误。谁能告诉我问题出在哪里?

谢谢

更新

回溯:

(myvenv) C:\Demo_1\mainsite>python manage.py createsuperuser --
database=users_db

Email: admin@test.com
Username: admin
First name: Admin
Last name: Test
Password: 
Password (again):
Traceback (most recent call last):
  File "C:\Demo_1\mainsite\manage.py", line 21, in <module>
    main()
  File "C:\Demo_1\mainsite\manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\danny\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\danny\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\danny\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\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute     
    return super().execute(*args, **options)
  File "C:\Users\danny\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\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle     
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
  File "C:\Demo_1\mainsite\accounts\models.py", line 98, in create_superuser
    user = self.create_user(
  File "C:\Demo_1\mainsite\accounts\models.py", line 94, in create_user
    user.save()
  File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save
    super().save(*args, **kwargs)
  File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 726, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 763, in save_base
    updated = self._save_table(
  File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 868, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 906, in _do_insert
    return manager._insert(
  File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 1270, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\compiler.py", line 1414, in execute_sql
    with self.connection.cursor() as cursor:
  File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 259, in cursor
    return self._cursor()
  File "C:\Users\danny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\dummy\base.py", line 20, in complain
    raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.

将你的 DataBase 设置为 :-

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'users_db',
        'USER': 'postgres',
        'PASSWORD': 'Trial_user123',
        'HOST': 'localhost',
        'PORT': '5432',
    }

    'content_db': {
        'NAME': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'content_II',
        'USER': 'postgres',
        'PASSWORD': 'Trial_user123',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

您必须以不同方式迁移两个数据库,例如:-

$ ./manage.py migrate --database=users_db
$ ./manage.py migrate --database=content_II

在不同的数据库中创建一个 superuser,例如 :-

./manage.py createsuperuser --database=users_db

尝试移除存档中的using

def create_user(...):
    ...
    user.save()


def create_superuser(...):
    ...
    user.save()

编辑:

刚刚注意到您的路由器没有 db_for_write(您写了两次 db_for_read):

    def db_for_write(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return 'users_db'
        return None