Django DB Settings 'Improperly Configured' Error
Asked Answered
B

7

171

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?

Burma answered 21/3, 2013 at 19:36 Comment(1)
Came across this when setting up a new project. I found it helpful to do unset DJANGO_SETTINGS_MODULE. I was running into an issue where I had set the env var in my .bashrcJermyn
H
266

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.

Hengist answered 21/3, 2013 at 19:42 Comment(12)
Thanks! That wasn't quite clear to me in the documentation, or maybe I read it & forgot by the time I needed to do it.Burma
Oddly it can't seem to find the 'mysite.settings' file, but I can see it sitting right there as mysite/settings.py. Ugh! I'm beginning to hate Django.Burma
completly strange to me too, because the function has some kind of static functionallaty so why setup this settings...Kelwin
@Pavel Anossov in 1.6.2 none of these works >>> from django.core.management import setup_environ Traceback (most recent call last): File "<stdin>", line 1, in <module> and sayth@sayth-TravelMate-5740G:~/Documents/Projects/FirstBlog$ django-admin.py shell --settings=FirstBlog.settings / ImportError: Could not import settings 'FirstBlog.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named FirstBlog.settings ImportError: cannot import name setup_environPrankster
Yes, setup_environ is removed in 1.6, but --settings should work. Are you sure your settings are in further FirstBlog.settings, and not just in settings in the current directory?Hengist
None of the above worked for me, but this one did: $ export DJANGO_SETTINGS_MODULE="my_project.settings"Rossy
Oh, and one of these export PYTHONPATH="$PYTHONPATH:'pwd'"Rossy
In PyCharm the place to do this is Run | Edit Configurations | (e.g. Unittests in project) | Configuration | Environment | Environment variables: DJANGO_SETTINGS_MODULE=(project directory name).settingsDungeon
this has been happening to me now that I split time w django and flask lolPerrie
I'm using Django 1.11 and the part of this answer featuring setup_environ doesn't work for me, but this question and answer does: #15049463Opuntia
@Rossy export DJANGO_SETTINGS_MODULE="my_project.settings" where did you put this?Bluebell
Any update on this thread? None of this works for me.Paregoric
C
41

In your python shell/ipython do:

from django.conf import settings

settings.configure()
Cowpea answered 11/7, 2015 at 2:1 Comment(1)
Apps aren't loaded yet.Culm
K
26

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)

Kierstenkieselguhr answered 1/10, 2017 at 19:28 Comment(4)
Thanks a lot, none of the other solutions have worked in my caseAmbulate
Work with python 2.7 tooHartsell
This .py should be placed at the root, which means it is along with manage.py. How do I place it inside random folders?Penley
It should be noted that this will only work if you put it at the top of your file, if you put it inside of something like if __name__ == "__main__": it won't work correctly :)Bivalve
A
12

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!

Archean answered 22/9, 2016 at 18:5 Comment(1)
same, on django 1.10, but while trying to run the command loaddataSlopwork
I
4

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
Icelandic answered 12/1, 2017 at 21:2 Comment(0)
U
3

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.

Underscore answered 17/9, 2016 at 20:42 Comment(0)
S
0

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

enter image description here

Stasiastasis answered 21/10, 2019 at 7:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.