Master One‑Off Django Scripts and Custom Management Commands
This guide explains how to write and run one‑off Python scripts and custom Django management commands for tasks like listing users, creating blog posts, and publishing or editing them, covering environment setup, model definitions, and command‑line argument handling.
Running One‑off Scripts in Django
When developing a Django project you may need one‑off scripts for tasks such as cleaning data or importing initial data. Two approaches exist: a plain Python script executed with python file_name.py or a Django‑admin command run via python manage.py command_name.
Plain Python Script Example
Example script list_users.py lists all users. Running it directly raises an ImproperlyConfigured error because Django settings are not loaded.
from django.contrib.auth import get_user_model
User = get_user_model()
users = User.objects.all()
for user in users:
print(f'user is {user.get_full_name()} and their username is {user.get_username()}')Fix by setting the environment variable and calling django.setup() before importing models.
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings')
import django
django.setup()
from django.contrib.auth import get_user_model
User = get_user_model()
users = User.objects.all()
for user in users:
print(f'user is {user.get_full_name()} and their username is {user.get_username()}')Creating a Blog App and Models
Run django-admin startapp posts and define Category and Post models that inherit from a common abstract CommonInfo with timestamps.
class CommonInfo(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
ordering = ('-created_at',)
class Category(CommonInfo):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Post(CommonInfo):
title = models.CharField(max_length=255)
category = models.ForeignKey(Category, related_name='posts', on_delete=models.PROTECT)
author = models.ForeignKey(User, related_name='posts', on_delete=models.PROTECT)
content = models.TextField()
published = models.BooleanField(default=False)
def __str__(self):
return f'{self.title} by {self.author.get_full_name()}'Script to Create a Blog Post
Script create_post.py sets Django settings, prompts the user to select a category and author, then creates a Post instance.
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'commands.settings')
import django
django.setup()
from django.contrib.auth import get_user_model
from posts.models import Category, Post
User = get_user_model()
def select_category():
categories = Category.objects.all().order_by('created_at')
print('Please select a category for your post:')
for category in categories:
print(f'{category.id}: {category}')
category_id = input()
return Category.objects.get(id=category_id)
def select_author():
users = User.objects.all()
print('Please select an author for your post:')
for user in users:
print(f'{user.id}: {user}')
user_id = input()
return User.objects.get(id=user_id)
def create_post():
title = input('Title of your post: ')
content = input('Long post content: ')
category = select_category()
author = select_author()
Post(title=title, content=content, category=category, author=author).save()
print('Post created successfully!')
if __name__ == '__main__':
create_post()Custom Django Management Commands
Custom commands live in app/management/commands. Example publish_post.py marks a post as published, accepting a positional post_id argument.
from django.core.management.base import BaseCommand, CommandError
from posts.models import Post
class Command(BaseCommand):
help = 'Marks the specified blog post as published.'
def add_arguments(self, parser):
parser.add_argument('post_id', type=int)
def handle(self, *args, **options):
try:
post = Post.objects.get(id=options['post_id'])
except Post.DoesNotExist:
raise CommandError(f'Post with id {options["post_id"]} does not exist')
if post.published:
self.stdout.write(self.style.ERROR(f'Post: {post.title} was already published'))
else:
post.published = True
post.save()
self.stdout.write(self.style.SUCCESS(f'Post: {post.title} successfully published'))Another command edit_post.py demonstrates optional arguments for updating a post's title or content.
from django.core.management.base import BaseCommand, CommandError
from posts.models import Post
class Command(BaseCommand):
help = 'Edits the specified blog post.'
def add_arguments(self, parser):
parser.add_argument('post_id', type=int)
parser.add_argument('-t', '--title', type=str, help='New title')
parser.add_argument('-c', '--content', type=str, help='New content')
def handle(self, *args, **options):
try:
post = Post.objects.get(id=options['post_id'])
except Post.DoesNotExist:
raise CommandError(f'Post with id {options["post_id"]} does not exist')
title = options.get('title')
content = options.get('content')
if title:
old_title = post.title
post.title = title
post.save()
self.stdout.write(self.style.SUCCESS(f'Post: {old_title} updated to {post.title}'))
if content:
post.content = content
post.save()
self.stdout.write(self.style.SUCCESS('Post content updated.'))
if not title and not content:
self.stdout.write(self.style.NOTICE('No changes provided.'))Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
