[Django]-ImportError and Django driving me crazy

3👍

import sys
sys.path.append ('/path/to/the/project')
from django.core.management import setup_environ
import settings
setup_environ(settings)

from app.models import MyModel

1👍

Whoa whoa whoa. You should never ever have to put your project name in any of your app code. You should be able to reuse app code across multiple projects with no changes. Pinax does this really well and I highly recommend checking it out for a lot of django best practices.

The worst thing you could do here is to hard code your absolute path into your app or settings. You shouldn’t do this because it will break during deployment unless you do some import local_settings hacking.

If you have to access the project root directory, try what pinax has in settings.py…

import os.path
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))

The thing is that it looks like you are trying to access the models module within the same app and this is waaay easier.

To import models.py inside scraper.py in the same directory just use import models or import models as app_models if you already have something named models in scraper.py (django.db.models for instance). Are you familiar with Python module conventions?

However, the best way is probably to stick with the django idiom, from … import … statement:

from app import models

If this doesn’t work automatically, then something is wrong in your settings.py.

0👍

You don’t indicate if project is located in /home/userspace/Development/. I’ll assume that it is.

Make sure there’s an (empty by default) file named __init__.py in project and another one in app.

EDIT: Next thing to try: Fire up the Python command line in the script’s directory and try the following:

import project
import project.app as app
import project.app.models as models
models.__dict__.keys()

Do they all work? If so, what is the last line’s output? If not, which dies first?

Leave a comment