gpt4 book ai didi

python - Django 数据库设置 'Improperly Configured' 错误

转载 作者:IT老高 更新时间:2023-10-28 12:23:42 25 4
gpt4 key购买 nike

Django (1.5) 对我来说工作得很好,但是当我启动 Python 解释器 (Python 3) 来检查一些东西时,我在尝试导入时遇到了最奇怪的错误 - from django.contrib.auth .models 导入用户 -

Traceback (most recent call last):
File "/usr/local/lib/python3.2/dist-packages/django/conf/__init__.py", line 36, in _setup
settings_module = os.environ[ENVIRONMENT_VARIABLE]
File "/usr/lib/python3.2/os.py", line 450, in __getitem__
value = self._data[self.encodekey(key)]
KeyError: b'DJANGO_SETTINGS_MODULE'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.2/dist-packages/django/contrib/auth/models.py", line 8, in <module>
from django.db import models
File "/usr/local/lib/python3.2/dist-packages/django/db/__init__.py", line 11, in <module>
if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES:
File "/usr/local/lib/python3.2/dist-packages/django/conf/__init__.py", line 52, in __getattr__
self._setup(name)
File "/usr/local/lib/python3.2/dist-packages/django/conf/__init__.py", line 45, in _setup
% (desc, ENVIRONMENT_VARIABLE))

django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES,
but settings are not configured. You must either define the environment
variable DJANGO_SETTINGS_MODULE or call settings.configure()
before accessing settings.

当它在 Python 解释器之外正常工作时,它怎么可能配置不正确?在我的 Django 设置中,DATABASES 设置是:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'django_db', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': 'zamphatta',
'PASSWORD': 'mypassword91',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}

...这是怎么配置不当的?

最佳答案

你不能只启动 Python 并检查,Django 不知道你想从事什么项目。您必须执行以下操作之一:

  • 使用python manage.py shell
  • 使用 django-admin.py shell --settings=mysite.settings(或您使用的任何设置模块)
  • 将操作系统中的 DJANGO_SETTINGS_MODULE 环境变量设置为 mysite.settings
  • (在 Django 1.6 中已删除)在 python 解释器中使用 setup_environ:

    from django.core.management import setup_environ
    from mysite import settings

    setup_environ(settings)

当然,第一种方法是最简单的。

关于python - Django 数据库设置 'Improperly Configured' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15556499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com