当我尝试用命令测试任何应用程序时(我注意到当我尝试使用fabric部署我的项目时,它使用了这个命令):

python manage.py test appname

我得到这个错误:

Creating test database for alias 'default'...
Got an error creating the test database: permission denied to create database

Type 'yes' if you would like to try deleting the test database 'test_finance', or 'no' to cancel

Syncdb命令似乎可以工作。我的数据库设置在settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'finance',                      # Or path to database file if using sqlite3.
        'USER': 'django',                      # Not used with sqlite3.
        'PASSWORD': 'mydb123',                  # Not used with sqlite3.
        'HOST': '127.0.0.1',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

当前回答

当Django运行测试套件时,它会创建一个新的数据库,在你的例子中是test_finance。以django为用户名的postgres用户没有创建数据库的权限,因此出现了错误信息。

当你运行migrate或syncdb时,Django不会尝试创建金融数据库,所以你不会得到任何错误。

你可以以超级用户的身份在postgres shell中运行以下命令,为django用户添加createdb权限。

=> ALTER USER django CREATEDB;

注意:ALTER USER中使用的用户名<username> CREATEDB;命令需要匹配Django设置文件中的数据库用户。在这种情况下,最初的海报,有用户django上面的答案。

其他回答

我也面临着同样的问题

皮测试

我修改了django的用户权限,这样它就可以在运行python测试用例时创建一个测试数据库。

修改用户名

当Django运行测试套件时,它会创建一个新的数据库,在你的例子中是test_finance。以django为用户名的postgres用户没有创建数据库的权限,因此出现了错误信息。

当你运行migrate或syncdb时,Django不会尝试创建金融数据库,所以你不会得到任何错误。

你可以以超级用户的身份在postgres shell中运行以下命令,为django用户添加createdb权限。

=> ALTER USER django CREATEDB;

注意:ALTER USER中使用的用户名<username> CREATEDB;命令需要匹配Django设置文件中的数据库用户。在这种情况下,最初的海报,有用户django上面的答案。

也许您将测试设置为暂停模式或作为后台工作。尝试使用bash shell中的fg命令。

我不久前也遇到了同样的问题。 这就是我如何能够解决django 3.10.6

首先使用这个命令通过终端进入dbshell

python3 manage.py dbshell

这将带您到您的项目dbie,如果您已经创建了一个。 另一种获取数据库的方法是:

sudo su postgres

然后:

psql

这将把您带到默认数据库。然后连接到你的项目db通过:

\c projectdb

在这一点上,使用这个命令来修复你的错误:

ALTER USER you CREATEDB;

用'\q'退出数据库;使用' Exit '退出postgres,然后运行:

python3 manage.py test app

错误将被修复,您的测试将通过

Found 1 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.
----------------------------------------------------------------------
Ran 1 test in 0.003s

OK
Destroying test database for alias 'default'...

错误提示用户没有创建数据库的足够权限。Django会在测试期间创建一个单独的数据库,这样我们原来的开发数据库就不会受到影响。

我们可能需要通过Postgres shell给予权限。

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': config('DB_NAME'),
    'USER': "myuser",
    'PASSWORD': config('DB_PASSWORD'),
    'HOST': config('DB_HOST'),
    'PORT': config('DB_PORT'),

    'TEST': {
        'NAME': 'test_nofoobar',
    },
}

}

正如设置建议的那样,在本例中,数据库用户的名称是myuser。因此,让我们启动Postgres shell并授予数据库创建权限。

sudo -u postgres psql


psql (14.5 (Ubuntu 14.5-1.pgdg22.04+1))

postgres=# ALTER ROLE myuser CREATEDB;
Output: ALTER ROLE