New django project: Cannot import name connections
Question: I'm having a problem with Django. If you could help me, I'd very much
appreciate it.

So, I've found lots of people with a similar problem, but none of the
"solutions" work for me. I'm learning how to use django and I've successfully
installed it.

But, I get an error when executing the import from the **init**.py file:

    
    
    from django.db import connections
    

Here's the error:

    
    
    raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
    ImportError: Could not import settings 'TestProject.settings' (Is it on sys.path?): cannot import name connections
    

The containing django folder is included on my PYTHONPATH, and my file
structure looks like this:

    
    
    TestProject
    --manage.py
    --TestProject
    ----__init__.py
    ----settings.py
        etc.
    

This is my manage.py file:

    
    
    #!/usr/bin/env python import os import sys
    
    if __name__ == "__main__":
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "TestProject.settings")
    
        from django.core.management import execute_from_command_line
    
        execute_from_command_line(sys.argv)
    

I don't really know how to troubleshoot this. I'm also new to Python, so
forgive me if this is completely obvious to someone else.

Thanks for your help.


Answer: This is a weird quirk indeed. I found the following to work in my program:

  1. Import django settings.
  2. Set the default environment.
  3. ACCESS e.g. SITE_ID (or another property, but just use e.g. SITE_ID) through settings.
  4. Finally, you should be able to import.

E.g.

    
    
    from django.conf import settings
    
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
    
    settings.SITE_ID
    

or use another variable like `DEBUG`; note.. this line does nothing.. it just
accesses the settings and seems to 'activate' the environment. You could also
do a simple print statement like `print settings.SITE_ID`, but that's not
necessary.)

    
    
    from myapp.models import MyModel, MyOtherModel
    

If you do everything in that order.. well it worked for me! The magic happens
when you access an actual setting before you do the import of a model.

I think this might be a bug/error in Django 1.5

