Hey everyone. I'm new to Python and Django, and I've been trying to get Django up and running for over 10 hours now. I've scoured the web, but with very little good documentation available, I thought I'd ask others for help. I'm trying to write a program which will connect to my database, but I can't even get started because Django is throwing fits. Here is the code I'm trying to run:

import os
import sys
from django.db import connection
print(sys.path)

It produces this error:

    from django.db import connection
  File "C:\Python27\lib\site-packages\django\db\__init__.py", line 11, in <module>
    if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES:
  File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 53, in __getattr__
    self._setup(name)
  File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 48, in _setup
    self._wrapped = Settings(settings_module)
  File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 134, in __init__
    raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'NewMKEProject.settings.py' (Is it on sys.path?): cannot import name connection

This is what the relevant portion of my settings.py file looks like:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'C:\\Users\\USER NAME\\Documents\\Aptana Studio 3 Workspace\\NewMKEProject\\mysql.db',
        'USER': 'MKExpenses',
        'PASSWORD': 'MY PASSWORD',
        'HOST': 'MY HOSTNAME',
        'PORT': '',                     
    }
}

And this is my manage.py file:

#!/usr/bin/env python
import os, sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "NewMKEProject.settings")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

So, I've taken everyone's suggestions and tried adding this just above the django import:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "NewMKEProject.settings")
but it doesn't work.

I've added the project folder and parent folder to PYTHONPATH. I've added the django folder as an external library. None of this has worked. Can anybody help me out?

I'm using Python 2.7.

Thanks for your help.

where are you running your little test script from? python/django can't find the settings.py module for some reason. are you running manage.py shell, or regular python interpreter? is "NewMKEProject" the name of a valid python package in your project (with __init__.py even if its empty)?

My directory structure is usually something like this:

.
..
MyProjectParentFolder/
    manage.py
    NewMKEProject/
        __init__.py
        settings.py

    MyTopLevelApp/
        __init__.py
        views.py
        models.py

This way, running manage.py I can use "MyTopLevelApp.models" and "NewMKEProject.settings" (although I access settings using django.conf.settings)...
I know there are other ways to structure django projects, such as putting apps under "NewMKEProject/", but this was how I learned to do it and I've grown to like it.

I'm running the script through Aptana Studio. My directory stucture is like this:

NewMKEProject/
    manage.py
    .project
    .pydevproject

    NewMKEProject/
        __init__.py
        settings.py
        urls.py
        wsgi.py

As far as I know, MKEProject is a valid package. I've added references to C:\Python27\Lib\site-packages\django and C:\Python27\Lib\site-packages\django\db to my PYTHONPATH. I don't understand why it can't find the library.

Does anyone have any ideas?

Sorry man, I guess I don't have enough info. It's easier when its on my machine and I can debug it myself. But anyway, errors like these usually happen when you try to run your Django app outside of Django's 'environment', which is why people are telling you to set the DJANGO_SETTINGS_MODULE variable. I also use aptana to build my website, which is a Django app. I don't really "run" or test my app with Aptana though. I use the command line and a browser.

Go to your terminal, change directory to wherever your manage.py is. When you run manage.py it will 'automagically' set up your sys.path and the DJANGO_SETTINGS_MODULE. If manage.py works then it's definately something to do with the way you are running your app under normal circumstances. Try some of these:

python manage.py validate
# catches easy errors in your models and other stuff

python manage.py syncdb
# this converts your python models to database tables, and also sets up django's
# own tables. Doing this when your model isn't ready may cause you a bit of a headache,
# depending on how good you are with your database, and what kind of database it is.
# (changing an SQLite table's columns was troublesome for me, even trying 'south' to migrate.
#  ...when I switched to PostgreSQL, the headaches went away.)

python manage.py shell
# django-friendly python interpreter, you can test code here
# and access your models by importing them:
# from myappname.models import mymodelname
# maybe something like: from NewMKEProject.models import [YourModelNameHere]

If validate works thats good, but that probably wasn't the problem anyway. If you can get into the shell then thats a good sign. If your database won't sync then it should give you an idea about what's going on with it. But these are just basic things to try, the real problem seems to be Django not finding it's settings.

If you are in the manage.py shell, try this:

from django.conf import settings
# imports your django app's configuration (along with your settings.py)
# if you can do this then your settings.py is good as far as python syntax is concerned.

As far as running it, I now use a local web server (apache2) to test, which I had to do some configuration for. My live project is also running on apache2. But before that, I used the Django builtin test server. To run the basic test server do this:

python manage.py runserver
# if this succeeds then everything is basically okay with your project and you can visit:
# http://127.0.0.1:8000

That little code-snippet you are testing with, try it in the manage.py shell. If you already know all of this stuff, or you have already tried it in the django-shell, I apologize. ...just trying to help. When you said you run it with 'aptana' it made me think that your app isn't being setup to run properly, which manage.py, runserver, and a properly configured wsgi.py will attempt to do. Further down the line, your live server may need other configurations, but this should at least get you up and running on your own machine.

commented: Nice to have one Django person here +12

I just spotted something in your code that I didn't even realize.

You aren't adding to the sys.path or setting the environment variable before you try that import. This is an excerpt from a little script I wrote for my project. It accesses my models/database but actually has nothing to do with my site. The server doesn't need to be running for me to use this script, and no one will ever see its results except me. But it still has to have the django environment loaded. So here's what you do when you just want to talk to your app (like manage.py shell does.):

import sys, os, os.path

# If this script is in the same directory as manage.py then you won't need 
# to add the sys.path. If it's not in the same directory, you will need this:

#sys.path.insert(0, "/main/path/to/NewMKEProject")


# Set django environment variable (if not set yet)
# ...you've already done this. but do it BEFORE you import anything from django.

if not os.environ.has_key("DJANGO_SETTINGS_MODULE"):
    os.environ["DJANGO_SETTINGS_MODULE"] = "wp_main.settings"

# NOTICE: You add the project dir to the sys.path when needed,
#         Then you add the DJANGO environment variable.
#         BEFORE trying to access django/app related modules.

Now that all of that is good, python is happy as long as it can find your modules. django is happy because it has its settings, which gives it the location for all of our app info.

# INSERT YOUR PROJECT-RELATED STUFF DOWN HERE
# Import welbornprod stuff (PUT YOUR MODELS/APPS HERE INSTEAD)
try:
    from blogger.models import wp_blog
    from projects.models import wp_project
except ImportError as eximp:
    print "unable to import welbornprod modules!\n" + \
          "be sure the sys.path is correct!\n\n" + str(eximp)
    sys.exit(1)

# What would I do with those imports? A lot of things. But a basic example is:
total_downloads = 0
for project in wp_project.objects.all():
    total_downloads += project.download_count

print "You have a total of " + str(total_downloads)+ " downloads from all of your projects."

print "You have " + str(wp_blog.objects.count()) + " blog posts."
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.