[Fixed]-How to execute external script in the Django environment


I would say creating a new Custom management command is the best way to achieve this goal.

But you can run your script in a django environment. I use this sometimes to run a oneoff script or some simple tests.

You have to set the environment variable DJANGO_SETTINGS_MODULE to your settings module and then you have to call django.setup()

I copied these lines from the manage.py script, you have to set the correct settings module!

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.local")

Here is a simple template script which I use sometimes:

# -*- coding: utf-8 -*-
import os
import django

#  you have to set the correct path to you settings module
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.local")

from project.apps.bla.models import MyModel

def run():
    # do the work
    m = MyModel.objects.get(pk=1)

if __name__ == '__main__':

It is important to note that all project imports must be placed after calling django.setup().


Many times you need scripts to play with db or more. But you need to the the django way i.e. the ORM and play with every thing that your project has.

You can checkout https://github.com/django-extensions/django-extensions

You create a scripts folder in your project home and write down a method run . the app provide you a way to run those scripts easily.
How to do it.

Step 1 – Install the package.
Step 2 – Create a scripts folder with init.py in project root, and add ‘django_extensions’ in your applications
Step 3- Create a file send_email_to_users.py in scripts folder. Simple Example.

from project.models import MyModel
from django.contrib.auth.models import User
from project.utils import send_email

def run():
    results = MyModel.objects.all()
    for res in results:

Now from command line you can run

python manage.py runscript send_mail_to_users


If its just a one off script,

import django

from myapp.models.import MyModel 

You need to have your environmental variable set up, so its easiest to run it from the IDE (make it part of the same project, right click on teh file and there should be a run option).

If you are looking for something to run on a production environment I would create a management command as suggested by DanEEStar.

Leave a comment