tags:

views:

244

answers:

3

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.
+5  A: 

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.

Alex Martelli
Thanks. So, is it reasonable to say that after setting up a Django project, it is REQUIRED to set 2 environment variables?-DJANGO_SETTINGS_MODULE-PYTHONPATH ..append the project path.?
TIMEX
lol, I think you're taking "I don't believe" too literally.
hasen j
@hasen, guess I have pretty high expectations from anybody named "alex";-).
Alex Martelli
@alex, the alternative is to make sure that you've "cut the dependencies" by shoving into sys.modules a fake version of some of the modules django's trying to import -- e.g., if you set `sys.modules['django.db']` to your own fake object that perfectly and entirely mimics what your models.py expects (and possibly other fakes along the way), it might be feasible to avoid environment settings. But, it would certainly be a "tour de force"!
Alex Martelli
+2  A: 

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 code something like this:

import sys, os

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

#do your stuff

Paul McMillan
+2  A: 

One alternative to messing about with the environment is to just write your script as a Django custom management command, which takes care of setting up the environment for you (along with other things like option parsing, etc).

Carl Meyer