开发者

ImportError and Django driving me crazy

OK, I have the following directory structure (it's a django project):

-> project
--> app

and within the app folder, there is a scraper.py file which needs to reference a class defined within models.py

I'm trying to do the following:


import urllib2
import os
import sys
import time
import datetime
import re
import BeautifulSoup

sys.path.append('/home/userspace/Development/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'

from project.app.models import ClassName

and this code just isn't working. I get an error of:

Traceback (most recent call last):
  File "scraper.py", line 14, in 
    from project.app.models import ClassN开发者_JAVA百科ame
ImportError: No module named project.app.models

This code above used to work, but broke somewhere along the line and I'm extremely confused as to why I'm having problems. On SnowLeopard using python2.5.


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


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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜