2
votes

I have a Python file thats part of the Django framework called facade.py

from django.conf import settings
from .gateway import Gateway

class Facade(object):


def __init__(self):
    self.gateway = Gateway(
        settings.password,
        settings.username,
        )

I want to test this code in my terminal window. This is what I have tried:

within virutal-env
python
>>> from my.apps.app.facade import Facade
>>> object = Facade()

but this give me the error ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

Why?

4
What version of django do you have? Where is that facade.py inside of the framework??? - mimoralea

4 Answers

15
votes

You should not do this in a plain Python shell. Start the shell with Django configured by doing ./manage.py shell instead of just python.

1
votes

Since this function uses Django, it's not sufficient to run it in a python shell. There are many things, like settings, models etc. which needs to be loaded for Django files to run.

You can't access and run django projects from python shell. Django doesn't know what project you want to work on.

You have to do one of these things:

  1. python manage.py shell
  2. Set DJANGO_SETTINGS_MODULE environment variable in your OS to mysite.settings
  3. Use setup_environ in the python interpreter:

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

The first one is easiest and best method. Run your code in the django shell.

0
votes

Try adding this:

from django.conf import settings

if not settings.configured:
    settings.configure()

Good luck!

0
votes

Like the error message says, you have to define the DJANGO_SETTINGS_MODULE environment variable:

In shell: export DJANGO_SETTINGS_MODULE=settings.module

And then start Python.