django-forms
4
总安装量
2
周安装量
#53077
全站排名
安装命令
npx skills add https://github.com/kjnez/claude-code-django --skill django-forms
Agent 安装分布
claude-code
2
opencode
1
cursor
1
codex
1
antigravity
1
gemini-cli
1
Skill 文档
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