Django数据库设置“配置不当”错误

171 投票
7 回答
187441 浏览
提问于 2025-04-17 19:55

Django(1.5)对我来说运行得很好,但当我打开Python解释器(Python 3)检查一些东西时,尝试导入 - from django.contrib.auth.models import User - 时却出现了奇怪的错误。

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.
    }
}

...那这怎么会配置不正确呢?

7 个回答

26

在2017年,使用的是django 1.11.5和python 3.6(根据评论,这个方法也适用于Python 2.7):

import django
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
django.setup()

你放置这段代码的.py文件应该在mysite文件夹里(也就是上级文件夹)

41

在你的Python命令行或者IPython中,输入以下内容:

from django.conf import settings

settings.configure()
266

你不能随便打开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)
    

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

撰写回答