Django DB设置“配置不正确”错误

问题:Django DB设置“配置不正确”错误

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

…这是如何配置不正确的?

Django (1.5) is workin’ fine for me, but when I fire up the Python interpreter (Python 3) to check some things, I get the weirdest error when I try importing – 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.

How could it be improperly configured, when it works fine outside the Python interpreter? In my Django settings, the DATABASES settings are:

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

…how is this improperly configured?


回答 0

您不能只启动Python并检查内容,Django不知道您要处理哪个项目。您必须执行以下操作之一:

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

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

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

You can’t just fire up Python and check things, Django doesn’t know what project you want to work on. You have to do one of these things:

  • Use python manage.py shell
  • Use django-admin.py shell --settings=mysite.settings (or whatever settings module you use)
  • Set DJANGO_SETTINGS_MODULE environment variable in your OS to mysite.settings
  • (This is removed in Django 1.6) Use setup_environ in the python interpreter:

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

Naturally, the first way is the easiest.


回答 1

在您的python shell / ipython中执行以下操作:

from django.conf import settings

settings.configure()

In your python shell/ipython do:

from django.conf import settings

settings.configure()

回答 2

在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(父之一)

In 2017 with django 1.11.5 and python 3.6 (from the comment this also works with Python 2.7):

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

The .py in which you put this code should be in mysite (the parent one)


回答 3

在Django 1.9上,我尝试django-admin runserver并得到了相同的错误,但是当我使用时python manage.py runserver,得到了预期的结果。这可能会解决很多人的这个错误!

On Django 1.9, I tried django-admin runserver and got the same error, but when I used python manage.py runserver I got the intended result. This may solve this error for a lot of people!


回答 4

就我而言,尝试通过PyCharm运行Django测试时遇到了这个问题。我认为这是因为PyCharm不会加载初始Django项目设置,即manage.py shell最初运行的设置。可以将它们添加到测试脚本的开头,也可以使用来运行测试manage.py test

版本:

  • Python 3.5(在virtualenv中)
  • PyCharm 2016.3.2专业版
  • Django 1.10

In my case, I got this when trying to run Django tests through PyCharm. I think it is because PyCharm does not load the initial Django project settings, i.e. those that manage.py shell runs initially. One can add them to the start of the testing script or just run the tests using manage.py test.

Versions:

  • Python 3.5 (in virtualenv)
  • PyCharm 2016.3.2 Professional
  • Django 1.10

回答 5

就我自己而言,在python2.7.11上运行的django 1.10.1中,我试图使用django-admin runserver而不是manage.py runserver在我的项目目录中启动服务器。

in my own case in django 1.10.1 running on python2.7.11, I was trying to start the server using django-admin runserver instead of manage.py runserver in my project directory.


回答 6

对于使用IntelliJ的人,通过这些设置,我可以从外壳程序(在Windows上)进行查询。

For people using IntelliJ, with these settings I was able to query from the shell (on windows).