They are 2 ways you can run Django as a standalone script. The first approach leverages on WSGI while the second approach uses Django admin commands by registering your own custom actions within manage.py. Why might you want to do this? In some instances they might be a need to run a script that performs some action, this could be an ad-hoc task such as data importing, data patching running custom logic that’s not user driven, perhaps even executing a cron job that fires your script on a periodical basis while still leveraging on your existing Django & ORM code base.
In this quick tutorial, we will be taking a look at the first approach which is relatively simple. If you understand how Django works then the answer pretty much lies inside your WSGI.py file that’s auto-generated for you if you’re using the django-admin startproject command to scaffold your initial Django project. You need to understand that all the bootstrapping and loading up of Django occurs directly within your wsgi.py and setting.py so we can create a script that calls the correct settings to run a Django script as a standalone program.
Let’s create a script called myscript.py which will be located into its own python module, that then loads up Django via WSGI. See code script below
location : djangoproject/scripts/myscript.py
from django.core.wsgi import get_wsgi_application
from django.contrib.auth.models import User
from django.utils import timezone
from django.conf import settings
# derive location to your django project setting.py
proj_path = os.path.split(os.path.abspath(os.path.dirname(__file__)))
# load your settings.py
# In essence you are actually loading up all the django components and settings
# so we gain access to djangos ORM
application = get_wsgi_application()
# run your custom script here
for django_admin_user in settings.ADMINS:
user = User.objects.get(email=django_admin_user)
user = User()
user.username = django_admin_user
user.first_name = str(django_admin_user).split()
user.last_name = str(django_admin_user).split()
user.email = django_admin_user
user.is_active = True
user.is_staff = True
user.is_superuser = True
user.date_joined = timezone.now()
Our little script doesn’t do much, it just checks if admin users exist in your database if a user is not found creates a new record or updates. Now all we need to do to execute the script is invoke it via our command prompt or Unix shell.
If we wished to take this a step further and run it periodically we could invoke this script via crontab or use supervisord to execute it as a service.
If you would like to learn more about Django and empower yourself with code checkout building your first Django app course in minutes, which covers lots of concepts to help you build your apps faster.