tags:

views:

52

answers:

1

Hi, I have a working django site and I'm trying to run a standalone script over its data. I am following this article, but can't get it to work. I have tried two approaches:

1)

import sys, os
sys.path.append(os.path.abspath('..'))

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

from mysite.main.models import Image
#from main.models import Image #should work too

2)

import sys, os
sys.path.append(os.path.abspath('..'))

from django.core.management import setup_environ 
from mysite import settings
#import settings #should work too
setup_environ(settings)

from mysite.main.models import Image

Both gives me "AttributeError: 'module' object has no attribute 'models'" raised from the module I am trying to import (main.models).

The script itself is located in the project root of a working site, with the "main" app properly installed and working. There should be no problem with settings or models.

A: 

I don't see any reason why your import statement should not work. Make sure that the module structure matches the import command. The module path should be mysite -> main -> models. Some developers add an extra apps module in a project such that the path becomes mysite -> apps -> main -> models. Ensure that this is not the case for you.

To check, do the following from the Django shell as well as the Python REPL.

from mysite.main.models import Image

If this doesn't work you'll need to troubleshoot your module structure.

Manoj Govindan
thanks, I tried "export PYTHONPATH=$PYTHONPATH:/projectpath/; export DJANGO_SETTINGS_MODULE=mysite.settings; django-admin.py shell" and the import did work! I am confused, any idea?
Lucie
OK, this is literally killing me. Since the AttributeError is rised from "main.models" module from the "class Image(imagekit.models.ImageModel):" class definition, I tried to change the imagekit module import THERE from this: "import imagekit" to verbose: "from mysite.apps.imagekit.models import ImageModel" and guess what, now it works. Big Fat Questionmark???
Lucie
Ah. For `import imagekit; imagekit.models.ImageModel` to work `imagekit` should be in your `PYTHONPATH`. I suspect it was not. However `from mysite.apps.imagekit.models import ImageModel` will work since `mysite` is in your `PYTHONPATH`. To test this add the location of `imagekit` to `PYTHONPATH` and try the first variant of import again.
Manoj Govindan
But... the import from django shell succeeded with only project path in `PYTHONPATH` (see above). There are other apps in the app directory (all except main) that are successfully imported, I insert the path in `settings.py`. `from imagekit.models import ImageModel` also works. I suspect there's some magic going on in imagekit, I didn't inspect their code.
Lucie