Django Components
Complete reference for all 33 Django components - patterns, APIs, configuration, and best practices for Python 3.10+ and Django 6.0.
Component Index
Models & Database
- Models - Model definition, field types, Meta options, inheritance, managers -> reference
- QuerySets - QuerySet API, field lookups, Q objects, F expressions, aggregation -> reference
- Migrations - Migration workflow, operations, data migrations, squashing -> reference
- Database Functions - Database functions, conditional expressions, full-text search -> reference
Views & HTTP
- Views - Function-based views, shortcuts (render, redirect, get_object_or_404) -> reference
- Class-Based Views - ListView, DetailView, CreateView, UpdateView, DeleteView, mixins -> reference
- URL Routing - URL configuration, path(), re_path(), namespaces, reverse() -> reference
- Middleware - Middleware architecture, built-in middleware, custom middleware -> reference
- Request & Response - HttpRequest, HttpResponse, JsonResponse, StreamingHttpResponse -> reference
Templates
- Templates - Template language, tags, filters, inheritance, custom template tags -> reference
Forms
- Forms - Form class, fields, widgets, ModelForm, formsets, validation -> reference
Admin
- Admin - ModelAdmin, list_display, fieldsets, inlines, actions, customization -> reference
Authentication & Security
- Authentication - User model, login/logout, permissions, groups, custom user models -> reference
- Security - CSRF, XSS, clickjacking, SSL, CSP, cryptographic signing -> reference
- Sessions - Session framework, backends, configuration -> reference
Caching
- Cache - Cache backends (Redis, Memcached, DB, filesystem), per-view/template caching -> reference
Signals
- Signals - Signal dispatcher, built-in signals (pre_save, post_save, etc.) -> reference
Communication
- Email - send_mail, EmailMessage, HTML emails, backends -> reference
- Messages - Messages framework, levels, storage backends -> reference
Testing
- Testing - TestCase, Client, assertions, RequestFactory, fixtures -> reference
Files & Static Assets
- Files - File objects, storage API, file uploads, custom storage -> reference
- Static Files - Static file configuration, collectstatic, ManifestStaticFilesStorage -> reference
Internationalization
- I18n - Translation, localization, timezones, message files -> reference
Serialization & Data
- Serialization - Serializers, JSON/XML formats, natural keys, fixtures -> reference
- Content Types - ContentType model, generic relations -> reference
- Validators - Built-in validators, custom validators -> reference
- Pagination - Paginator, Page objects, template integration -> reference
Async & Tasks
- Async - Async views, async ORM, sync_to_async, ASGI -> reference
- Tasks - Tasks framework, task backends, scheduling -> reference
Configuration & CLI
- Settings - Settings reference by category, splitting settings -> reference
- Management Commands - Built-in commands, custom commands, call_command -> reference
- Logging - Logging configuration, handlers, Django loggers -> reference
Deployment
- Deployment - WSGI, ASGI, Gunicorn, Uvicorn, static files, checklist -> reference
Quick Patterns
Define a Model
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
content = models.TextField()
published = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey('auth.User',
class Meta:
ordering = ['-created_at']
def __str__(self):
return self.title
Define a URL + View
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('articles/<int:pk>/', views.article_detail, name='article_detail'),
]
# views.py
from django.shortcuts import render, get_object_or_404
def article_detail(request, pk):
article = get_object_or_404(Article, pk=pk)
return render(request, 'articles/detail.html', {'article': article})
Class-Based View
from django.views.generic import ListView, DetailView
class ArticleListView(ListView):
model = Article
queryset = Article.objects.filter(published=True)
paginate_by = 20
class ArticleDetailView(DetailView):
model = Article
slug_field = 'slug'
QuerySet Filtering
from django.db.models import Q, F, Count
# Complex filtering
articles = Article.objects.filter(
Q(title__icontains='django') | Q(content__icontains='django'),
published=True,
).exclude(
author__is_active=False
).annotate(
comment_count=Count('comments')
).order_by('-created_at')
Form with Validation
from django import forms
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ['title', 'slug', 'content', 'published']
def clean_title(self):
title = self.cleaned_data['title']
if len(title) < 5:
raise forms.ValidationError('Title must be at least 5 characters.')
return title
Cache a View
from django.views.decorators.cache import cache_page
@cache_page(60 * 15) # 15 minutes
def article_list(request):
articles = Article.objects.filter(published=True)
return render(request, 'articles/list.html', {'articles': articles})
Signal Receiver
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=Article)
def notify_on_publish(sender, instance, created, **kwargs):
if instance.published and created:
send_notification(instance)
Management Command
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Process pending articles'
def add_arguments(self, parser):
parser.add_argument('--limit', type=int, default=100)
def handle(self, *args, **options):
count = process_articles(limit=options['limit'])
self.stdout.write(self.style.SUCCESS(f'Processed {count} articles'))
Test Case
from django.test import TestCase
class ArticleTests(TestCase):
def setUp(self):
self.article = Article.objects.create(
title='Test Article',
slug='test-article',
content='Content here',
published=True,
)
def test_article_detail_view(self):
response = self.client.get(f'/articles/{self.article.pk}/')
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'Test Article')
Best Practices
- Target Python 3.10+ and Django 6.0 with type hints where helpful
- Use class-based views for CRUD; function-based views for custom logic
- Prefer select_related/prefetch_related to avoid N+1 queries
- Use F expressions for database-level operations instead of Python
- Apply migrations atomically - one logical change per migration
- Use Django's cache framework with Redis or Memcached in production
- Write TestCase tests with assertions specific to Django (assertContains, assertRedirects)
- Use custom user models from the start (AUTH_USER_MODEL)
- Enable CSRF protection everywhere - never use @csrf_exempt without good reason
- Use environment variables for secrets - never commit SECRET_KEY or database credentials
- Deploy with Gunicorn/Uvicorn behind a reverse proxy (nginx)
- Run manage.py check --deploy before every production deployment
Source: krzysztofsurdy/code-virtuoso — distributed by TomeVault.
1---2name: django-components3description: Comprehensive reference for all 33 Django framework components with Python 3.10+ and Django 6.0 patterns. Use when the user asks to implement, configure, or troubleshoot any Django component including Models, QuerySets, Views, Templates, Forms, Admin, Authentication, Caching, Testing, Middleware, Signals, or Deployment. Covers ORM patterns, class-based views, template tags, form validation, admin customization, async support, and Django best practices. Use when this capability is needed.4---56# Django Components78Complete reference for all 33 Django components - patterns, APIs, configuration, and best practices for Python 3.10+ and Django 6.0.910## Component Index1112### Models & Database13- **Models** - Model definition, field types, Meta options, inheritance, managers -> [reference](references/models.md)14- **QuerySets** - QuerySet API, field lookups, Q objects, F expressions, aggregation -> [reference](references/querysets.md)15- **Migrations** - Migration workflow, operations, data migrations, squashing -> [reference](references/migrations.md)16- **Database Functions** - Database functions, conditional expressions, full-text search -> [reference](references/database-functions.md)1718### Views & HTTP19- **Views** - Function-based views, shortcuts (render, redirect, get_object_or_404) -> [reference](references/views.md)20- **Class-Based Views** - ListView, DetailView, CreateView, UpdateView, DeleteView, mixins -> [reference](references/class-based-views.md)21- **URL Routing** - URL configuration, path(), re_path(), namespaces, reverse() -> [reference](references/urls.md)22- **Middleware** - Middleware architecture, built-in middleware, custom middleware -> [reference](references/middleware.md)23- **Request & Response** - HttpRequest, HttpResponse, JsonResponse, StreamingHttpResponse -> [reference](references/request-response.md)2425### Templates26- **Templates** - Template language, tags, filters, inheritance, custom template tags -> [reference](references/templates.md)2728### Forms29- **Forms** - Form class, fields, widgets, ModelForm, formsets, validation -> [reference](references/forms.md)3031### Admin32- **Admin** - ModelAdmin, list_display, fieldsets, inlines, actions, customization -> [reference](references/admin.md)3334### Authentication & Security35- **Authentication** - User model, login/logout, permissions, groups, custom user models -> [reference](references/auth.md)36- **Security** - CSRF, XSS, clickjacking, SSL, CSP, cryptographic signing -> [reference](references/security.md)37- **Sessions** - Session framework, backends, configuration -> [reference](references/sessions.md)3839### Caching40- **Cache** - Cache backends (Redis, Memcached, DB, filesystem), per-view/template caching -> [reference](references/cache.md)4142### Signals43- **Signals** - Signal dispatcher, built-in signals (pre_save, post_save, etc.) -> [reference](references/signals.md)4445### Communication46- **Email** - send_mail, EmailMessage, HTML emails, backends -> [reference](references/email.md)47- **Messages** - Messages framework, levels, storage backends -> [reference](references/messages.md)4849### Testing50- **Testing** - TestCase, Client, assertions, RequestFactory, fixtures -> [reference](references/testing.md)5152### Files & Static Assets53- **Files** - File objects, storage API, file uploads, custom storage -> [reference](references/files.md)54- **Static Files** - Static file configuration, collectstatic, ManifestStaticFilesStorage -> [reference](references/static-files.md)5556### Internationalization57- **I18n** - Translation, localization, timezones, message files -> [reference](references/i18n.md)5859### Serialization & Data60- **Serialization** - Serializers, JSON/XML formats, natural keys, fixtures -> [reference](references/serialization.md)61- **Content Types** - ContentType model, generic relations -> [reference](references/content-types.md)62- **Validators** - Built-in validators, custom validators -> [reference](references/validators.md)63- **Pagination** - Paginator, Page objects, template integration -> [reference](references/pagination.md)6465### Async & Tasks66- **Async** - Async views, async ORM, sync_to_async, ASGI -> [reference](references/async.md)67- **Tasks** - Tasks framework, task backends, scheduling -> [reference](references/tasks.md)6869### Configuration & CLI70- **Settings** - Settings reference by category, splitting settings -> [reference](references/settings.md)71- **Management Commands** - Built-in commands, custom commands, call_command -> [reference](references/management-commands.md)72- **Logging** - Logging configuration, handlers, Django loggers -> [reference](references/logging.md)7374### Deployment75- **Deployment** - WSGI, ASGI, Gunicorn, Uvicorn, static files, checklist -> [reference](references/deployment.md)7677## Quick Patterns7879### Define a Model8081```python82from django.db import models8384class Article(models.Model):85 title = models.CharField(max_length=200)86 slug = models.SlugField(unique=True)87 content = models.TextField()88 published = models.BooleanField(default=False)89 created_at = models.DateTimeField(auto_now_add=True)90 author = models.ForeignKey('auth.User', on_delete=models.CASCADE)9192 class Meta:93 ordering = ['-created_at']9495 def __str__(self):96 return self.title97```9899### Define a URL + View100101```python102# urls.py103from django.urls import path104from . import views105106urlpatterns = [107 path('articles/<int:pk>/', views.article_detail, name='article_detail'),108]109110# views.py111from django.shortcuts import render, get_object_or_404112113def article_detail(request, pk):114 article = get_object_or_404(Article, pk=pk)115 return render(request, 'articles/detail.html', {'article': article})116```117118### Class-Based View119120```python121from django.views.generic import ListView, DetailView122123class ArticleListView(ListView):124 model = Article125 queryset = Article.objects.filter(published=True)126 paginate_by = 20127128class ArticleDetailView(DetailView):129 model = Article130 slug_field = 'slug'131```132133### QuerySet Filtering134135```python136from django.db.models import Q, F, Count137138# Complex filtering139articles = Article.objects.filter(140 Q(title__icontains='django') | Q(content__icontains='django'),141 published=True,142).exclude(143 author__is_active=False144).annotate(145 comment_count=Count('comments')146).order_by('-created_at')147```148149### Form with Validation150151```python152from django import forms153154class ArticleForm(forms.ModelForm):155 class Meta:156 model = Article157 fields = ['title', 'slug', 'content', 'published']158159 def clean_title(self):160 title = self.cleaned_data['title']161 if len(title) < 5:162 raise forms.ValidationError('Title must be at least 5 characters.')163 return title164```165166### Cache a View167168```python169from django.views.decorators.cache import cache_page170171@cache_page(60 * 15) # 15 minutes172def article_list(request):173 articles = Article.objects.filter(published=True)174 return render(request, 'articles/list.html', {'articles': articles})175```176177### Signal Receiver178179```python180from django.db.models.signals import post_save181from django.dispatch import receiver182183@receiver(post_save, sender=Article)184def notify_on_publish(sender, instance, created, **kwargs):185 if instance.published and created:186 send_notification(instance)187```188189### Management Command190191```python192from django.core.management.base import BaseCommand193194class Command(BaseCommand):195 help = 'Process pending articles'196197 def add_arguments(self, parser):198 parser.add_argument('--limit', type=int, default=100)199200 def handle(self, *args, **options):201 count = process_articles(limit=options['limit'])202 self.stdout.write(self.style.SUCCESS(f'Processed {count} articles'))203```204205### Test Case206207```python208from django.test import TestCase209210class ArticleTests(TestCase):211 def setUp(self):212 self.article = Article.objects.create(213 title='Test Article',214 slug='test-article',215 content='Content here',216 published=True,217 )218219 def test_article_detail_view(self):220 response = self.client.get(f'/articles/{self.article.pk}/')221 self.assertEqual(response.status_code, 200)222 self.assertContains(response, 'Test Article')223```224225## Best Practices226227- Target **Python 3.10+** and **Django 6.0** with type hints where helpful228- Use **class-based views** for CRUD; function-based views for custom logic229- Prefer **select_related/prefetch_related** to avoid N+1 queries230- Use **F expressions** for database-level operations instead of Python231- Apply **migrations** atomically - one logical change per migration232- Use **Django's cache framework** with Redis or Memcached in production233- Write **TestCase** tests with assertions specific to Django (assertContains, assertRedirects)234- Use **custom user models** from the start (AUTH_USER_MODEL)235- Enable **CSRF protection** everywhere - never use @csrf_exempt without good reason236- Use **environment variables** for secrets - never commit SECRET_KEY or database credentials237- Deploy with **Gunicorn/Uvicorn** behind a reverse proxy (nginx)238- Run **manage.py check --deploy** before every production deployment239240---241> Source: [krzysztofsurdy/code-virtuoso](https://github.com/krzysztofsurdy/code-virtuoso) — distributed by [TomeVault](https://tomevault.io).242<!-- tomevault:4.0:skill_md:2026-06-15 -->