python
49 lines · 1 tab
Priya Sharma
Jan 2026
1 tab
import csv
from django.core.management.base import BaseCommand, CommandError
from products.models import Product, Category
class Command(BaseCommand):
help = 'Import products from a CSV file'
def add_arguments(self, parser):
parser.add_argument('csv_file', type=str, help='Path to CSV file')
parser.add_argument(
'--clear',
action='store_true',
help='Clear existing products before import',
)
def handle(self, *args, **options):
if options['clear']:
Product.objects.all().delete()
self.stdout.write(self.style.WARNING('Cleared existing products'))
try:
with open(options['csv_file'], 'r') as f:
reader = csv.DictReader(f)
created_count = 0
for row in reader:
category, _ = Category.objects.get_or_create(
name=row['category']
)
Product.objects.create(
name=row['name'],
description=row['description'],
price=row['price'],
category=category,
)
created_count += 1
self.stdout.write(
self.style.SUCCESS(
f'Successfully imported {created_count} products'
)
)
except FileNotFoundError:
raise CommandError(f'File {options["csv_file"]} not found')
except KeyError as e:
raise CommandError(f'Missing required column: {e}')
1 file · python
Explain with highlit
Management commands are perfect for scripts that need Django's ORM and settings. I create them in management/commands/ and extend BaseCommand. The add_arguments method defines CLI options using argparse. I use self.stdout.write with style helpers for colored output. For long-running imports, I show progress and handle errors gracefully with try-except. Commands are testable with call_command() and can be scheduled with cron or Celery beat. This keeps admin scripts organized and discoverable via ./manage.py help.
Related snips
python
import os
import stat
for root, _dirs, files in os.walk('/etc'):
for name in files:
path = os.path.join(root, name)
Python security audit script for exposed risky filesystem state
python
auditing
host-security
by Kai Nakamura
1 tab
python
class Product(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
cost = models.DecimalField(max_digits=10, decimal_places=2)
margin = models.DecimalField(max_digits=5, decimal_places=2, blank=True)
Django model signals vs overriding save
django
python
models
by Priya Sharma
2 tabs
rust
use clap::Parser;
#[derive(Parser, Debug)]
#[command(author, version, about)]
struct Args {
#[arg(short, long)]
clap for CLI argument parsing with derive macros
rust
cli
clap
by Marcus Chen
1 tab
python
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
Django URL namespacing and reverse lookups
django
python
urls
by Priya Sharma
3 tabs
python
import graphene
from graphene_django import DjangoObjectType
from blog.models import Post, Comment
class PostType(DjangoObjectType):
Django GraphQL with Graphene
django
python
graphql
by Priya Sharma
2 tabs
python
from django.db.models import Count, Avg, Sum, Q, F
from django.views.generic import TemplateView
from products.models import Product, Order, OrderItem
class DashboardView(TemplateView):
Django aggregation with annotate for statistics
django
python
database
by Priya Sharma
1 tab
Share this code
Here's the card — post it anywhere.