Every few days you need to create sample data, clean up old records, or send a report from the database. The cleanest way to do that in Django is to package these jobs as a custom management command — a Python file placed in the right location, run with python manage.py command_name. You should use it whenever you have a recurring data task that doesn’t need a web interface.

The problem

Many projects start with standalone scripts for seeding data or running one-off tasks:

# seed_data.py — hand-run script, lying loose in the repo
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myshop.settings")
django.setup() # forget this line and it fails immediately
from shop.models import Product
for i in range(100):
Product.objects.create(name=f"Sample product {i}", price=100000)

Each script has to bootstrap Django itself with django.setup(), there’s no standard way to pass arguments, no colored logs, and no shared logic between tasks. In production, forgetting to set the correct DJANGO_SETTINGS_MODULE is a disaster.

The solution

Put your command in shop/management/commands/seed_products.py (every app gets its own management/commands directory — remember to create an __init__.py in each folder):

import random
from django.core.management.base import BaseCommand
from shop.models import Product
class Command(BaseCommand):
help = "Create sample data for the Product table"
def add_arguments(self, parser):
parser.add_argument(
"--count", type=int, default=10,
help="Number of sample products to create (default: 10)",
)
def handle(self, *args, **options):
count = options["count"]
for i in range(1, count + 1):
Product.objects.create(
name=f"Sample product {i}",
price=random.randint(50_000, 500_000),
)
self.stdout.write(
self.style.SUCCESS(f"Created {count} sample products.")
)

Run it:

python manage.py seed_products --count 50

This command beats a standalone script in four ways: Django loads settings itself, so no django.setup() is needed; add_arguments() gives you standard arguments with free --help; self.stdout.write() + self.style give colored logs that clearly separate success from errors; and the command is versioned with the app — anyone who pulls the code can use it immediately.

Apply it to your project

Call the command from other code (tests, admin views, CI scripts) with call_command:

from django.core.management import call_command
call_command("seed_products", count=50)

To run on a schedule — say, cleaning up expired records every night — just have cron call python manage.py command_name in the correct production environment. If the project already has Celery, consider turning the command into a Celery Beat task for centralized scheduling. Practical tip: name commands after the action (cleanup_expired_sessions, seed_products) rather than something generic, because python manage.py --help lists them for the whole team to use.

Related posts

Frequently asked questions

Where must the command file live?

In any app: app_name/management/commands/command_name.py. Both the management and commands folders need an __init__.py file, and the app must be in INSTALLED_APPS.

Can I call a command from code or tests?

Yes. Use from django.core.management import call_command, then call_command("seed_products", count=50). Very handy for seeding data in tests or triggering from an admin action.

How do I run it on a schedule?

The simplest way is a cron entry calling python manage.py command_name in the right environment (virtualenv + production settings). If you already have Celery, put it in Celery Beat for centralized management.

How should the command report errors?

Raise CommandError("error message") — Django prints the error to stderr and returns exit code 1, so cron/CI picks up the failure signal.

Does the command work in production?

Yes — just deploy the code normally and run with the production DJANGO_SETTINGS_MODULE. Commands use the ORM, so they follow transactions and permissions like every other part of Django.

References