Django Python Script Execution: 2 Methods
There are typically two ways to execute a Python script in Django.
- commands for managing
- The name of the command is
.py. - execute the following command in python: “manage.py
“
Sample code:
# myapp/management/commands/my_command.py
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'My custom command'
def handle(self, *args, **options):
# Your script logic here
print('Hello, Django!')
- Directly calling Python scripts: In a Django project, Python scripts can be directly called, but it’s important to note that they need to be run in the root directory of the Django project. Otherwise, it may result in a failure to import Django modules.
Example code:
# script.py
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
import django
django.setup()
# Your script logic here
print('Hello, Django!')
After that, you can run the python script.py in the project’s root directory to execute the script.