且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

django测试应用程序错误 - 创建测试数据库时出错:权限被拒绝创建数据库

更新时间:2022-11-25 08:41:43

Django运行测试套件,它创建一个新的数据库,在您的情况下为test_finance。具有用户名 django 的postgres用户没有创建数据库的权限,因此出现错误消息。



当您运行syncdb,Django不会尝试创建财务数据库,因此您不会收到任何错误。



您可以通过运行django用户将createb权限添加到作为超级用户在postgress shell中执行以下命令(此堆栈溢出回答)。

  => ALTER USER django CREATEDB; 

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


When I try to test any app with command (I noticed it when I tried to deploy myproject using fabric, which uses this command):

python manage.py test appname

I get this error:

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 command seems to work. My database settings in 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.
    }
}

When Django runs the test suite, it creates a new database, in your case test_finance. The postgres user with username django does not have permission to create a database, hence the error message.

When you run syncdb, Django does not try to create the finance database, so you don't get any errors.

You can add the createdb permission to the django user by running the following command in the postgress shell as a superuser (hat tip to this stack overflow answer).

=> ALTER USER django CREATEDB;

Note: The username used in the ALTER USER <username> CREATEDB; command needs to match the database user in your Django settings files. In this case, the original poster, had the user as django the above answer.