How to call a Django 3 command from anywhere on your system
Here is an example script that allows you to call the commands of your Django application from any folder on your system. This tutorial is based on version 3.1.2 of Django.
You just have to fill in the lines preceded by ‘UPDATE THIS’.
#!/usr/bin/env python
import os
import django
#### UPDATE THIS: Add and fill this block if your Django app is not in your PYTHONPATH
import sys
sys.path.append("/path/to/your/django/app")
####
#### UPDATE THIS
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "nameof.yourmodule")
django.setup()
def main():
"""Run administrative tasks."""
try:
from django.core.management import call_command
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
#### UPDATE THIS
call_command('name_of_my_command', 'my_args', my_option='my_option_value')
if __name__ == '__main__':
main()