Django 测试:创建测试数据库时出错:复制数据库的权限被拒绝 "template_postgis"

Django Test: error creating the test database: permission denied to copy database "template_postgis"

我正在为 running tests 设置 Django 项目。但我遇到以下错误:

Got an error creating the test database: permission denied to copy database "template_postgis"

注意:我的默认应用程序数据库工作正常。 issue is happening while running tests.

完整的堆栈跟踪如下:

moin@moin-pc:~/workspace/mozio$ python manage.py test --verbosity=3
nosetests --verbosity=3
nose.config: INFO: Ignoring files matching ['^\.', '^_', '^setup\.py$']
Creating test database for alias 'default' ('test_my_db')...
Got an error creating the test database: permission denied to copy database "template_postgis"

Type 'yes' if you would like to try deleting the test database 'test_mozio_db_test', or 'no' to cancel: yes
Destroying old test database 'default'...
Got an error recreating the test database: must be owner of database test_mozio_db_test

下面是setting.py的数据库配置:

POSTGIS_VERSION = (2, 2, 2)

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'my_db',
        'USER': 'my_user',
        'PASSWORD': 'my_pass',
        'HOST': '<HOST_IP',
        'PORT': '',
        'TEST': {
            'NAME': 'test_my_db',
        },
    }
}

对此有任何帮助吗?以下是我尝试过的步骤:


编辑: 解决上述问题后,我也收到错误消息:

django.db.utils.ProgrammingError: type "geometry" does not exist
LINE 5:     "polygon" geometry(POLYGON,4326) NOT NULL,

更新了我的回答以解决这两个问题。

我终于找到了解决这个问题的方法。问题是当我创建template_postgis时,我没有将它设置为template

您可以通过以下方式检查它:

SELECT * FROM pg_database;

您可以通过 运行 为 template_postgis 设置 datistemplate=true 来修复它:

update pg_database set datistemplate=true where datname='template_postgis';

之后,如果您收到与 geometry 相关的错误,例如:

django.db.utils.ProgrammingError: type "geometry" does not exist
LINE 5:     "polygon" geometry(POLYGON,4326) NOT NULL,

那是因为你需要给数据库添加扩展名postgix。为了解决这个问题,将 postgis 添加到 template_postgis,例如:

psql -d psql -d template_postgis -c 'create extension postgis;'

注意:您必须是超级用户才能创建此扩展。

首先正确安装软件包。

sudo apt-get update
sudo apt-get install python-pip python-dev libpq-dev postgresql postgresql-contrib

在安装过程中会自动创建 postgres 用户。

 sudo su - postgres

您现在应该处于 postgres 用户的 shell 会话中。通过键入以下内容登录到 Postgres 会话:

 psql

 CREATE DATABASE myproject;

在你的settings.py.

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