Deepankar Bajpeyi
Deepankar Bajpeyi

Reputation: 5859

python: Django import fails asking me to define DJANGO_SETTINGS_MODULE

I am newbee in Django.I finished the Django Tutorial once from the official djangoproject site.Not saying I know everything now, but everything worked perfectly for me till I was referring that website.
I started referring to the Practical Django projects book and somewhere in my models I tried to import :

from django.contrib.auth.models import User

gives me an import error :

ImportError Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined `

What is really going on here ? I have been successfully importing all the packages till now then why this sudden error ?

Upvotes: 0

Views: 260

Answers (1)

Alasdair
Alasdair

Reputation: 308799

How are you running the code that gives you the error? If you are importing the models.py in the shell, use the Django shell command

./manage.py shell

If you are trying the import in another script, you have to set the environment variable DJANGO_SETTINGS_MODULE manually.

import os

if 'DJANGO_SETTINGS_MODULE' not in os.environ:
    os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

This requires myproject to be in your python path.

See this similar Stack Overflow question for futher discussion.

Upvotes: 1

Related Questions