python snakes
Programming & Web Development

Using Django models in external Python scripts

Since Django 1.4 the syntax to import you models in external scripts has changed. The setup_environ method has been deprecated for a while and it no longer exists in Django 1.6.

Assuming you’re using a virtualenv and your script is one directory outside the main Django project directory structure.

my_directory/
  |
  |---> virtualenv/
  |---> my_project/   < --- Django project files
  |---> my_script.py

I use this for Django 1.6 integration in my_script.py:

sys.path.append(os.path.join(os.path.dirname(__file__), 'my_project'))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings")
from django.conf import settings

from my_app.models import MyModel

About the author

Gabriel Saldaña Gabriel Saldaña is a web developer, photographer and free software advocate. Connect with him on and Twitter

Creative Commons License
Using Django models in external Python scripts by Gabriel Saldaña, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Share Alike 2.5 Mexico License.

Standard

2 thoughts on “Using Django models in external Python scripts

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>