Why am I getting this error in Django?


Question

I have a script that imports a models.py from an app, but it will not import! I don't believe I am supposed to manually create an "export DJANGO..." environment variable...I'm doing something else wrong.

 Traceback (most recent call last):
      File "parse.py", line 8, in ?
        from butterfly.flower.models import Channel, Item
      File "/home/user/shri/butterfly/flower/models.py", line 1, in ?
        from django.db import models
      File "/usr/lib/python2.4/site-packages/django/db/__init__.py", line 10, in ?
        if not settings.DATABASE_ENGINE:
      File "/usr/lib/python2.4/site-packages/django/utils/functional.py", line 269, in __getattr__
        self._setup()
      File "/usr/lib/python2.4/site-packages/django/conf/__init__.py", line 38, in _setup
        raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
    ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
1
20
10/29/2009 3:23:08 AM

Accepted Answer

I don't believe I am supposed to manually create an "export DJANGO..." environment variable...

Manually or otherwise, you are supposed to ensure that variable is in the environment before you import a Django models file -- not sure what the causes are for your disbelief, but, whatever they may be, that disbelief is ill-founded.

16
10/29/2009 3:26:35 AM

You need to properly import your settings file. If you don't import the django environment variables first, your import will fail as you've noticed. You need to code something like:

import os

# Set the DJANGO_SETTINGS_MODULE environment variable.
os.environ['DJANGO_SETTINGS_MODULE'] = "myproject.settings"

#do your stuff


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon