Django数据库设置’Improperly Configured’错误

问题:

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

…这是不正确的配置?

回答:

你不能只是启动Python并检查事情,Django不知道你想要工作的项目。你必须做这些事情之一:

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

     
    从mysite导入设置

    setup_environ(设置)

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

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: Django DB Settings 'Improperly Configured' Error

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

4 + 5 =