I’ve often needed to integrate standalone Python scripts into Django projects. Whether it’s for data processing, automation, or backend tasks, running Python scripts inside Django can be tricky if you’re not familiar with the best approaches.
In this article, I’ll walk you through different methods to run Python scripts within a Django application. I’ll share practical examples and tips based on real-world projects, specifically tailored for developers working in the USA or anywhere else.
Let’s get right in!
Why Run Python Scripts Inside Django?
Django is a useful web framework, but sometimes you want to execute Python scripts that perform tasks outside the usual request-response cycle. For example:
- Processing large datasets for a US-based sales analytics dashboard
- Automating email reports for your marketing team
- Running machine learning models to recommend products
Embedding or running these scripts efficiently is key to building scalable Django apps.
Read Create an Email Sender App in Django
Method 1: Run Python Scripts Using Django Management Commands
One of the cleanest ways to run Python scripts in Django is by creating custom management commands. These commands behave like built-in Django commands (runserver, migrate) and can be executed via the command line.
How to Create a Custom Management Command
Let me show you a working example where we run a Python script that processes US sales data and outputs a summary report.
Step 1: Create the Command Directory
Inside one of your Django apps (e.g., sales), create the following folder structure:
sales/
management/
commands/
__init__.py
process_sales.pyStep 2: Write Your Command (process_sales.py)
from django.core.management.base import BaseCommand
from sales.models import Sale
from datetime import datetime
class Command(BaseCommand):
help = 'Process US sales data and generate a summary report'
def add_arguments(self, parser):
parser.add_argument(
'--year',
type=int,
help='Year of sales data to process',
default=datetime.now().year
)
def handle(self, *args, **kwargs):
year = kwargs['year']
sales = Sale.objects.filter(date__year=year, country='USA')
total_sales = sales.count()
total_revenue = sum(sale.amount for sale in sales)
self.stdout.write(f"Sales Report for {year} in USA")
self.stdout.write(f"Total Sales: {total_sales}")
self.stdout.write(f"Total Revenue: ${total_revenue:,.2f}")Step 3: Run Your Command
Open your terminal and run:
python manage.py process_sales --year 2023I executed the above example code and added the screenshot below.

You’ll see a summary of sales for the specified year.
Check out Get HTML Code from Rich Text in Python Django
Method 2: Run Python Scripts Inside Django Views
Sometimes you want to run a Python script as part of a web request, for example, when a user clicks a button on your website.
How to Run a Python Script in a Django View
Let’s say you have a Python script that analyzes user behavior on your US e-commerce site. You can call this script inside a Django view and return the results on a webpage.
Example View
from django.shortcuts import render
from sales.analytics import analyze_user_behavior # Your standalone Python script
def user_behavior_view(request):
# Run the Python function
result = analyze_user_behavior()
# Pass the results to the template
return render(request, 'user_behavior.html', {'result': result})Example Python Script (sales/analytics.py)
def analyze_user_behavior():
# Imagine complex logic here analyzing user clicks, purchases, etc.
# For demo, return a simple dictionary
return {
'most_active_hour': '8 PM',
'top_product': 'Wireless Headphones',
'average_session_time': '15 minutes',
}I executed the above example code and added the screenshot below.

This method is straightforward but be cautious: long-running scripts can slow down your web response. For heavy tasks, consider asynchronous options (covered next).
Read To-Do List in Python Django
Method 3: Run Python Scripts Asynchronously with Celery
For tasks that take time — like generating large reports or sending bulk emails — running scripts synchronously inside views or commands can block your application.
Celery is a popular task queue that lets you run Python scripts asynchronously in the background.
Setting Up Celery in Django
- Install Celery and a message broker like Redis:
pip install celery redis- Create a
celery.pyfile in your Django project root:
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
app = Celery('myproject')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()- Define a Celery task in your app (
sales/tasks.py):
from celery import shared_task
from sales.models import Sale
@shared_task
def generate_sales_report(year):
sales = Sale.objects.filter(date__year=year, country='USA')
total_sales = sales.count()
total_revenue = sum(sale.amount for sale in sales)
# Save report to database or send email
return {'year': year, 'total_sales': total_sales, 'total_revenue': total_revenue}- Call this task asynchronously in your views or commands:
from sales.tasks import generate_sales_report
def trigger_report(request):
generate_sales_report.delay(2023)
return HttpResponse("Report generation started.")This way, your Django app remains responsive, and the heavy script runs in the background.
Check out the Calculator App in Python Django
Method 4: Use subprocess to Run External Python Scripts
If you have standalone Python scripts outside Django that you want to execute, you can use Python’s built-in subprocess module.
Example of Running an External Script
Suppose you have a script scripts/us_sales_analysis.py that you want to run from a Django view.
import subprocess
from django.http import HttpResponse
def run_external_script(request):
result = subprocess.run(['python', 'scripts/us_sales_analysis.py'], capture_output=True, text=True)
if result.returncode == 0:
return HttpResponse(f"Script output: <pre>{result.stdout}</pre>")
else:
return HttpResponse(f"Error: <pre>{result.stderr}</pre>", status=500)This method gives you flexibility, but be careful with security and performance.
Read Python Django “Module not found” error.
Best Practices When Running Python Scripts in Django
- Avoid long-running scripts in views: Use asynchronous tasks like Celery.
- Use management commands for scheduled or manual runs: Easier to maintain and schedule.
- Keep scripts modular: Separate business logic from Django code for reusability.
- Handle errors gracefully: Always catch exceptions and provide meaningful logs.
- Secure your subprocess calls: Validate input and avoid running untrusted scripts.
Running Python scripts in Django can be easy or complex, depending on your needs. From management commands to asynchronous Celery tasks, you have multiple options to choose from.
I hope this guide helps you integrate your Python scripts seamlessly into your Django projects. If you have any questions or want to share your tips, feel free to leave a comment below!
Other Django articles you may also like:
- Query in Descending and Ascending in Python Django
- Parse JSON in Python Django
- Python Django “Template does not exist” error

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.