2

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?

1
  • What version of django do you have? Where is that facade.py inside of the framework??? Commented Sep 19, 2013 at 12:52

4 Answers 4

15

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks I did not know you could do this.
You also didn't knew you should... ;)
1

Try adding this:

from django.conf import settings

if not settings.configured:
    settings.configure()

Good luck!

Comments

1

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.