Using django for CLI tool

While django is primarily for web apps it has a powerful and easy to use ORM that can be used for CLI apps as well. To use django script as a standalone script without a webserver, all you need to do is to add the following to the top of the file.

import os, sys
if __name__ == '__main__':
    # Setup environ
    sys.path.append(os.getcwd())
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings")

    # Setup django
    import django
    django.setup()

    # now you can import your ORM models 

Leave a Comment