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
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.4---5
6# Django Components
7
8Complete reference for all 33 Django components -- patterns, APIs, configuration, and best practices for Python 3.10+ and Django 6.0.
9
10## Component Index
11
12### Models & Database
13- **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)
17
18### Views & HTTP
19- **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)
24
25### Templates
26- **Templates** -- Template language, tags, filters, inheritance, custom template tags -> [reference](references/templates.md)
27
28### Forms
29- **Forms** -- Form class, fields, widgets, ModelForm, formsets, validation -> [reference](references/forms.md)
30
31### Admin
32- **Admin** -- ModelAdmin, list_display, fieldsets, inlines, actions, customization -> [reference](references/admin.md)
33
34### Authentication & Security
35- **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)
38
39### Caching
40- **Cache** -- Cache backends (Redis, Memcached, DB, filesystem), per-view/template caching -> [reference](references/cache.md)
41
42### Signals
43- **Signals** -- Signal dispatcher, built-in signals (pre_save, post_save, etc.) -> [reference](references/signals.md)
44
45### Communication
46- **Email** -- send_mail, EmailMessage, HTML emails, backends -> [reference](references/email.md)
47- **Messages** -- Messages framework, levels, storage backends -> [reference](references/messages.md)
48
49### Testing
50- **Testing** -- TestCase, Client, assertions, RequestFactory, fixtures -> [reference](references/testing.md)
51
52### Files & Static Assets
53- **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)
55
56### Internationalization
57- **I18n** -- Translation, localization, timezones, message files -> [reference](references/i18n.md)
58
59### Serialization & Data
60- **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)
64
65### Async & Tasks
66- **Async** -- Async views, async ORM, sync_to_async, ASGI -> [reference](references/async.md)
67- **Tasks** -- Tasks framework, task backends, scheduling -> [reference](references/tasks.md)
68
69### Configuration & CLI
70- **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)
73
74### Deployment
75- **Deployment** -- WSGI, ASGI, Gunicorn, Uvicorn, static files, checklist -> [reference](references/deployment.md)
76
77## Quick Patterns
78
79### Define a Model
80
81```python
82from django.db import models
83
84class 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)
91
92 class Meta:
93 ordering = ['-created_at']
94
95 def __str__(self):
96 return self.title
97```
98
99### Define a URL + View
100
101```python
102# urls.py
103from django.urls import path
104from . import views
105
106urlpatterns = [
107 path('articles/<int:pk>/', views.article_detail, name='article_detail'),
108]
109
110# views.py
111from django.shortcuts import render, get_object_or_404
112
113def article_detail(request, pk):
114 article = get_object_or_404(Article, pk=pk)
115 return render(request, 'articles/detail.html', {'article': article})
116```
117
118### Class-Based View
119
120```python
121from django.views.generic import ListView, DetailView
122
123class ArticleListView(ListView):
124 model = Article
125 queryset = Article.objects.filter(published=True)
126 paginate_by = 20
127
128class ArticleDetailView(DetailView):
129 model = Article
130 slug_field = 'slug'
131```
132
133### QuerySet Filtering
134
135```python
136from django.db.models import Q, F, Count
137
138# Complex filtering
139articles = Article.objects.filter(
140 Q(title__icontains='django') | Q(content__icontains='django'),
141 published=True,
142).exclude(
143 author__is_active=False
144).annotate(
145 comment_count=Count('comments')
146).order_by('-created_at')
147```
148
149### Form with Validation
150
151```python
152from django import forms
153
154class ArticleForm(forms.ModelForm):
155 class Meta:
156 model = Article
157 fields = ['title', 'slug', 'content', 'published']
158
159 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 title
164```
165
166### Cache a View
167
168```python
169from django.views.decorators.cache import cache_page
170
171@cache_page(60 * 15) # 15 minutes
172def article_list(request):
173 articles = Article.objects.filter(published=True)
174 return render(request, 'articles/list.html', {'articles': articles})
175```
176
177### Signal Receiver
178
179```python
180from django.db.models.signals import post_save
181from django.dispatch import receiver
182
183@receiver(post_save, sender=Article)
184def notify_on_publish(sender, instance, created, **kwargs):
185 if instance.published and created:
186 send_notification(instance)
187```
188
189### Management Command
190
191```python
192from django.core.management.base import BaseCommand
193
194class Command(BaseCommand):
195 help = 'Process pending articles'
196
197 def add_arguments(self, parser):
198 parser.add_argument('--limit', type=int, default=100)
199
200 def handle(self, *args, **options):
201 count = process_articles(limit=options['limit'])
202 self.stdout.write(self.style.SUCCESS(f'Processed {count} articles'))
203```
204
205### Test Case
206
207```python
208from django.test import TestCase
209
210class 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 )
218
219 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```
224
225## Best Practices
226
227- Target **Python 3.10+** and **Django 6.0** with type hints where helpful
228- Use **class-based views** for CRUD; function-based views for custom logic
229- Prefer **select_related/prefetch_related** to avoid N+1 queries
230- Use **F expressions** for database-level operations instead of Python
231- Apply **migrations** atomically -- one logical change per migration
232- Use **Django's cache framework** with Redis or Memcached in production
233- 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 reason
236- Use **environment variables** for secrets -- never commit SECRET_KEY or database credentials
237- Deploy with **Gunicorn/Uvicorn** behind a reverse proxy (nginx)
238- Run **manage.py check --deploy** before every production deployment