Django
Python
Django shell
script execution
programming tutorial

How to execute a Python script from the Django shell?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

The Django shell is useful because it starts Python with your project settings, models, and application imports already available. You can execute a script from that environment, but the cleanest method depends on whether the script is a quick one-off, a reusable helper, or something that should really become a management command.

Prefer Importing a Callable for Repeatable Scripts

If the script will be used more than once, put the logic in a normal Python function and import it from the Django shell. This is cleaner than pasting code or executing a raw file as a string.

python
1# myapp/scripts/backfill_profiles.py
2from django.contrib.auth import get_user_model
3
4def run():
5    User = get_user_model()
6    for user in User.objects.filter(profile__isnull=True):
7        user.profile_set.create()

Then run it from the shell:

bash
python manage.py shell
python
from myapp.scripts.backfill_profiles import run

run()

This keeps the code importable and testable. It also behaves like normal application code rather than something that only works inside one terminal session.

Use runpy for a Standalone File

If you already have a script file on disk and want to execute it from an interactive Django shell session, runpy.run_path() is a better option than exec(open(...).read()). It runs the file in a separate namespace and makes the intent clearer.

python
import runpy

runpy.run_path("scripts/fix_customer_flags.py")

Because the shell already loaded Django settings, the file can import models, settings, and project modules normally.

Use Shell Redirection for Non-Interactive Runs

If you do not need an interactive prompt, you can still use Django's shell command to execute the script with Django initialized.

bash
python manage.py shell < scripts/fix_customer_flags.py

This is handy for one-off maintenance work because the code runs with the project environment in place without requiring you to paste anything into the terminal manually.

Know When the Script Should Become a Management Command

The Django shell is great for experiments, data inspection, and temporary maintenance tasks. It is less suitable for repeatable operational jobs that need arguments, logging, help text, or team-wide documentation.

If the code is becoming part of your normal workflow, convert it into a custom management command. That gives you a stable interface, a clear entry point, and a safer place to handle options and validation.

Be Careful With Database Writes

Scripts run from the Django shell have full ORM access. That is powerful, but it also means a mistake can change real data quickly. For anything nontrivial, inspect the queryset first and consider a transaction.

python
1from django.db import transaction
2from myapp.models import Invoice
3
4with transaction.atomic():
5    invoices = Invoice.objects.filter(status="pending")
6    for invoice in invoices:
7        invoice.status = "queued"
8        invoice.save(update_fields=["status"])

The shell is convenient precisely because it removes setup friction. That convenience makes discipline more important, not less.

Common Pitfalls

  • Using exec(open(...).read()) for logic that should really live in an importable function or module.
  • Running the shell from the wrong working directory and then being surprised when relative paths fail.
  • Making database updates without first checking which rows the queryset will affect.
  • Keeping a frequently used operational script as an undocumented shell snippet instead of promoting it to a management command.
  • Assuming shell-executed code is harmless experimentation even though it has full access to the Django project and database.

Summary

  • For reusable code, write a function and import it into python manage.py shell.
  • For standalone files, runpy.run_path() is clearer than raw exec().
  • Use shell redirection when you want Django initialization without an interactive session.
  • Promote recurring jobs to management commands.
  • Treat shell scripts carefully because they run with full ORM and settings access.

Course illustration
Course illustration

All Rights Reserved.