Make stand-alone python scripts to load Django environment


Sometimes we need to make some executable scripts inside Django applications that standalone and independent.
Usually this for generate / processing data without accessing / open any Django views.

For instance, I have “Posts” application, I need to modified all Post and send them to some 3rdparty.
So, this will be:

1
2
3
4
project
   |___ posts
         |____ utils
                 |____ generate_post.py

Then, in generate_post.py, I just load Django environment by :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import os
import sys

CURRENT = os.path.dirname(__file__)
PROJECT_PATH = os.path.abspath(os.path.join(CURRENT, "..", ".."))

sys.path.append(PROJECT_PATH)

import settings
from django.core.management import setup_environ

setup_environ(settings)

# From here, you can start import any app models here
# Do whatever you want here

Yes, it’s simple. Basically, you need to load “settings” using “setup_environ”.
Before import settings, you should make sure to load django project path.


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.