2

I am just getting this django app (also an inexperienced python user) running and wanted to be able to access the models.

I have the following:

import sys, os
sys.path.append('/Users/jx/dev/arc/django/second/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
from django.db import models
from testproject.models import Location
loc=Location.objects.get(name='Joes')

print loc.name

but get the following error:

Traceback (most recent call last):
  File "zz.py", line 6, in <module>
    from testproject.models import Location
ImportError: No module named testproject.models

Is there a way I can determine whether it is loading the settings.py correctly? Or is there an obvious syntax issue? Should the PYTHONPATH reflect the locations for the models (it currently doesn't if print os.environ)?

thx

1
  • i'm a dope - i didn't have the script in the django project directory. I guess this is mandatory for path info.
    – timpone
    May 27, 2011 at 3:37

3 Answers 3

6

Django has support for creating custom django-admin commands (documentation).

Very useful for creating command line scripts that access the model.

0
2
  1. Make sure you have added the folder containing testproject folder to sys.path. For example if you have the following structure /foo/bar/testproject/models.py then you should add /foo/bar to sys.path
  2. Make sure the testproject folder has a __init__.py file in it (which can be empty).
1

If it wasn't loading your settings correctly then from django.db import models would have failed. As it is, your testproject package isn't found; add the directory containing testproject/ to sys.path.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.