Skip to content

Using Django on CLI

May 2, 2007

Using Django for Non-Web Applications

Django is designed to be a web application framework. Unfortunately applications are not always purely ‘web-based’. Sometimes you need a background processing module that is clearly not web-based (CLI perhaps). Of course instead of reverting to plain SQL you would like to re-use your existing Django-based easy to use models and database API.

Basically all you need to do is to import your the settings module of your project (site) before importing your models. This allows Django to know which database to connect before hand. It is pretty much a tricky task but fortunately after digging core, I found a piece of code in django/core/management.py that might just do the trick.

And here what I got out of it. Just place this code in one of your Django app folder and its ready to go. You can then execute it like a regular any Python code.

#!/usr/bin/env python

def setup_environ():
    import os
    import sys

    # Expand the file path
    path_component = os.path.abspath(__file__).split(os.sep)

    # Add the project to sys.path so it's importable.
    project_name = path_component[-3]
    project_directory = os.sep.join(path_component[:-2])
    sys.path.append(os.path.join(project_directory, '..'))
    project_module = __import__(project_name, {}, {}, [''])
    sys.path.pop()

    # Set DJANGO_SETTINGS_MODULE
    os.environ['DJANGO_SETTINGS_MODULE'] =
        '%s.settings' % project_name

if __name__ == '__main__':
    setup_environ()

# Import your Django models here
import ProjectName.ApplicationName.models

# Your code as usual ...

Notes:

  1. The script will need to reside in the same directory as your models.py. Despite that, you would need to state the complete import path when importing your models. i.e., import ProjectName.ApplicationName.models instead of just import models.
  2. This code will most likely also run on Windows :)

Feel free to tell me (comment below) if it works for you or if something is wrong :)
Good Luck and Have fun!

From → Django

Leave a Comment

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: