无法使用Django连接PostgreSQL

5

我在postgresql中创建了一个名为testdb1的数据库,现在我想把它连接到我的django应用程序上。但是当我运行python manage.py syncdb时,出现错误信息django.db.utils.OperationalError: FATAL: database "testdb1" does not exist。但这个数据库确实存在,如下所示:

archit@archit-Inspiron-5520:~/Documents/DjangoLabs/gswd$ psql -U postgres
Password for user postgres: 
psql (9.1.14)
Type "help" for help.

postgres=# \connect testdb1
You are now connected to database "testdb1" as user "postgres".
testdb1=# \d
          List of relations
 Schema |  Name   | Type  |  Owner   
--------+---------+-------+----------
 public | company | table | postgres
(1 row)

settings.py文件中,我有以下代码:

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

/etc/postgresql/9.1/main/pg_hba.conf文件中:
# Database administrative login by Unix domain socket
local   all             postgres                                md5

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local   replication     postgres                                peer
#host    replication     postgres        127.0.0.1/32            md5
#host    replication     postgres        ::1/128                 md5
local   all         postgres                          md5

编辑:

\du 命令会显示:

testdb1=# \du
                             List of roles
 Role name |                   Attributes                   | Member of 
-----------+------------------------------------------------+-----------
 archit    | Superuser, Create role, Create DB, Replication | {}
 postgres  | Superuser, Create role, Create DB, Replication | {}

非常感谢您的帮助。


我在部署一个项目时遇到了同样的错误。虽然我不记得具体是什么,但解决方案非常简单。例如,尝试在settings.py中添加PORT或其他类似的内容。 - DAKZH
我曾经遇到过类似的问题,但我的情况是在pgAdmin上在本地机器上创建了数据库,但在服务器的命令行中自动将所有内容转换为小写。在我的设置文件中,它是大写的,因此Django无法识别该数据库。这似乎不是这里的问题,但其他人可能会遇到类似的问题。 - bmackley
2个回答

1
删除数据库并重新创建数据库。
在settings.py中写入'PORT'='5432'或'5433',因为这是所有postgresql的常用端口。
然后执行syncdb或migrate。

你安装了psycopg2吗? - jatinkumar patel
是的,我已经安装了它。 - Archit Verma

-2

即使删除了表格,它仍然会给出相同的错误。 - Archit Verma
你正在将端口设置为空字符串,请尝试使用默认端口或从字典中删除它。并且请遵循教程!您必须使用syncdb或migrate(取决于Django的版本)构建数据库。 - Ramon Moraes
@ArchitVerma 在删除后,你需要重新创建数据库再执行syncdb。 - Raja Simon
@rajasimon根本不需要删除任何内容。他可以使用ORM构建他们的数据库/表格。 - Ramon Moraes
@rajasimon 我同意。但是表格已经存在不应该是问题。 - Archit Verma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接