django-forms
Django Forms
Philosophy
- Prefer ModelForm for model-backed forms
- Keep validation logic in forms, not views
- Always handle and display form errors
- Use
commit=Falsewhen you need to modify the instance before saving
Validation
Field-level (clean_<field>):
- Validate and transform a single field
- Return the cleaned value or raise
ValidationError - Use for: format checks, uniqueness, normalization
Cross-field (clean):
- Call
super().clean()first - Access multiple fields via
cleaned_data - Use
self.add_error(field, message)for field-specific errors - Use for: password confirmation, conditional requirements
View Integration
- Check
request.methodexplicitly - Instantiate form with
request.POSTfor POST, empty for GET - Use
form.save(commit=False)to set additional fields (e.g., author) - Return redirect on success, re-render with form on error
HTMX handling:
- Check
request.headers.get("HX-Request")for HTMX requests - Return partial template on success/error for HTMX
- Use
HX-Triggerheader to notify other components
Templates
- Display
form.non_field_errorsfor cross-field errors - Display
field.errorsfor each field - Use partial templates (
_form.html) for HTMX responses - Include loading indicator with
hx-indicator
Widgets
- Override in
Meta.widgetsdict - Set HTML attributes via
attrsparameter - Common:
Textarea(attrs={"rows": 5}),DateTimeInput(attrs={"type": "datetime-local"})
Formsets
- Use
inlineformset_factoryfor related model collections - Validate both form and formset:
form.is_valid() and formset.is_valid() - Pass
instancefor editing existing parent objects
Pitfalls
- Validating in views instead of forms
- Silently redirecting without checking
is_valid() - Forgetting
commit=Falsewhen setting related fields - Not displaying form errors to users
More from kjnez/claude-code-django
htmx-patterns
HTMX patterns for Django including partial templates, hx-* attributes, and dynamic UI without JavaScript. Use when building interactive UI, handling AJAX requests, or creating dynamic components.
31django-templates
Django template patterns including inheritance, partials, tags, and filters. Use when working with templates, creating reusable components, or organizing template structure.
30pytest-django-patterns
pytest-django testing patterns, Factory Boy, fixtures, and TDD workflow. Use when writing tests, creating test factories, or following TDD red-green-refactor cycle.
24celery-patterns
Celery task patterns including task definition, retry strategies, periodic tasks, and best practices. Use when implementing background tasks, scheduled jobs, or async processing.
15django-models
Django model design patterns emphasizing fat models/thin views, QuerySet optimization, and domain logic encapsulation. Use when designing models, optimizing queries, implementing business logic, or working with the ORM.
14django-extensions
Django-extensions management commands for project introspection, debugging, and development. Use when exploring URLs, models, settings, database schema, running scripts, or profiling performance. Triggers on questions about Django project structure, model fields, URL routes, or requests to run development servers.
12