How to Access Your Django Models from External Python Scripts

Spent a good portion of time on this over the weekend, and it turned out to be frustrating enough and the answers available incomplete enough for me to want to document this here briefly.I wanted to be able to populate my Django models from an external script by simply calling MyObject.save() .  My particular case was scraping some information off of a website using BeautifulSoup then inserting it into my Django application, where it would show up and be editable from the admin section.  It turned out that I had a major problem with environment variables, so after a lot of reading and some trial and error, the following should work for you.

import osimport syssys.path.append('/path/to/the/directory/above/your/project')os.environ['DJANGO_SETTINGS_MODULE'] = 'yourproject.settings'from  yourproject.yourapp.models import YourModel

To be a little more clear: f your project is in “/Users/username/myproject”, append “/Users/username” to your system path.  This clears up your environment so that when you set the location of your django settings file using the dot notation, it knows where to look.As always, if you have any questions or comments or a better way to do this, let me know.  I’m using this on Snow Leopard with a trunk SVN checkout of Django.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s