如何在 Windows 7 上使用命令 CMD 从 python django 访问和配置 postgresql 数据库

Posted

技术标签:

【中文标题】如何在 Windows 7 上使用命令 CMD 从 python django 访问和配置 postgresql 数据库【英文标题】:How to access and configure postgresql database from python django on Windows 7 using a command CMD 【发布时间】:2019-07-03 11:29:05 【问题描述】:

当我运行 CMD Windows 7 命令时:

python manage.py makemigrations

我收到一个错误:

django.core.exceptions.ImproperlyConfigured: 'django.db.backends.postgresql' isn't an available database backend. Try using 'django.db.backends.XXX' where XXX is one of : 'mysql', 'oracle', 'sqlite3'

我已经安装了 postgresql 10,并在我的 django setting.py 中将 postgresql 设置为 per the documentation

我想在 Windows 7 上使用 CMD 从 python django 应用程序访问 postgresql 数据库。

我使用的是 Windows 7,python 3.7.1; PostgreSQL 10; django 2.1.5。我已经尝试了多次搜索解决方案,但我没有得到相关的解决方案。我已经使用 pgAdmin 4 v4 创建了我的 postgresql 数据库,但无法在 Windows 7 上使用 CMD 命令访问它以执行以下命令:

python manage.py showmigrations/makemigrations/migrate 

所有都发送与主题中显示的相同的错误。

settings.py 文件从这里开始...

"""
Django settings for my_sample project.

Generated by 'django-admin startproject' using Django 2.1.5.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'secret key string was here but now is purposely removed'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'my_sample.urls'

TEMPLATES = [
    
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': 
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        ,
    ,
]

WSGI_APPLICATION = 'my_sample.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = 
    'default': 
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'my_sample',
        'USER': 'postgres',
        'PASSWORD': 'my_password',
        'HOST':'localhost',
        'PORT': '5432',
    



# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    ,
    
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    ,
    
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    ,
    
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    ,
]


# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, javascript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

#settings.py file ends here...

#manage.py file starts here...

#!/usr/bin/env python
import os
import sys

if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_sample.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

#manage.py file ends here...

当我跑步时:

python manage.py migrate

我希望得到:

Running migrations: 
No migrations to apply. 

相反,我得到:

django.core.exceptions.ImproperlyConfigured: 'django.db.backends.postgresql' isn't an available database backend. Try using 'django.db.backends.XXX' where XXX is one of : 'mysql', 'oracle', 'sqlite3'

【问题讨论】:

【参考方案1】:

将您的应用添加到 INSTALLED_APPS 列表中,如下所示:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'yoursampleapp'
]

然后运行 ​​makemigrations:

python manage.py makemigrations

【讨论】:

我添加了我的应用程序“my_sample”,保存了 setting.py 文件并从 cmd Windows 7 重新运行 python manage.py makemigrations 命令,但我仍然遇到同样的错误。【参考方案2】:

您是否安装了 psycopg2 软件包?见https://docs.djangoproject.com/en/2.1/topics/install/#database-installation。

或运行pip install psycopg2

【讨论】:

是的,我通过“pip install psycopg2”安装了psycopg2 如果它抱怨引擎值,错误应该是 'django.db.backends.postgresql_psycopg2' 而不是 'django.db.backends.postgresql'。解决方案可能就在这个领域。尝试手动输入以避免编码错误。 我已尝试将其删除并重新键入为 'django.db.backends.postgresql_psycopg2' 但仍然发送错误 'django.core.exceptions.ImproperlyConfigured: 'django.db.backends.postgresql' is' t 可用的数据库后端。尝试使用“django.db.backends.XXX”,其中 XXX 是以下之一:“mysql”、“oracle”、“sqlite3” 语句“上述异常是以下异常的直接原因:......”之前的第一个错误是“ ModuleNotFoundError: No module named 'django.db .backends.postgresql'"。似乎在检查文件“...\lib\site-packages\django\db\utils.py, line 110 in load_backend”然后文件“...\lib\importlib\_init_.py,import_module 中的第 127 行

以上是关于如何在 Windows 7 上使用命令 CMD 从 python django 访问和配置 postgresql 数据库的主要内容,如果未能解决你的问题,请参考以下文章

从cmd调用Windows 7中的通知气球消息?

如何在 cmd(Windows) 上创建多个空文件

Windows 7 命令提示符:如何从命令行执行批处理脚本?

Windows系统下如何在cmd命令窗口中切换Python2.7和Python3.6

在Windows 7中更改命令提示符的默认启动目录

如何在Python中调用Windows的cmd命令?