django-forms

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Django Forms

Django表单

Philosophy

设计理念

  • Prefer ModelForm for model-backed forms
  • Keep validation logic in forms, not views
  • Always handle and display form errors
  • Use
    commit=False
    when you need to modify the instance before saving
  • 优先为模型关联表单使用ModelForm
  • 将验证逻辑放在表单中,而非视图
  • 始终处理并显示表单错误
  • 当需要在保存前修改实例时,使用
    commit=False

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
字段级验证 (
clean_<field>
):
  • 验证并转换单个字段
  • 返回清理后的值或抛出
    ValidationError
  • 适用场景:格式检查、唯一性验证、标准化处理
跨字段验证 (
clean
):
  • 先调用
    super().clean()
  • 通过
    cleaned_data
    访问多个字段
  • 使用
    self.add_error(field, message)
    添加字段专属错误信息
  • 适用场景:密码确认、条件性要求验证

View Integration

视图集成

  • Check
    request.method
    explicitly
  • Instantiate form with
    request.POST
    for 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-Trigger
    header to notify other components
  • 显式检查
    request.method
  • POST请求时用
    request.POST
    实例化表单,GET请求时使用空表单
  • 使用
    form.save(commit=False)
    设置额外字段(例如:作者)
  • 成功时返回重定向,错误时重新渲染带表单的页面
HTMX处理:
  • 检查
    request.headers.get("HX-Request")
    判断是否为HTMX请求
  • 成功/错误时为HTMX返回部分模板
  • 使用
    HX-Trigger
    通知其他组件

Templates

模板

  • Display
    form.non_field_errors
    for cross-field errors
  • Display
    field.errors
    for each field
  • Use partial templates (
    _form.html
    ) for HTMX responses
  • Include loading indicator with
    hx-indicator
  • 显示
    form.non_field_errors
    以展示跨字段错误
  • 为每个字段显示
    field.errors
  • 使用部分模板(
    _form.html
    )作为HTMX响应
  • 通过
    hx-indicator
    添加加载指示器

Widgets

小部件(Widgets)

  • Override in
    Meta.widgets
    dict
  • Set HTML attributes via
    attrs
    parameter
  • Common:
    Textarea(attrs={"rows": 5})
    ,
    DateTimeInput(attrs={"type": "datetime-local"})
  • Meta.widgets
    字典中覆盖默认小部件
  • 通过
    attrs
    参数设置HTML属性
  • 常见示例:
    Textarea(attrs={"rows": 5})
    DateTimeInput(attrs={"type": "datetime-local"})

Formsets

表单集(Formsets)

  • Use
    inlineformset_factory
    for related model collections
  • Validate both form and formset:
    form.is_valid() and formset.is_valid()
  • Pass
    instance
    for editing existing parent objects
  • 使用
    inlineformset_factory
    处理关联模型集合
  • 同时验证表单和表单集:
    form.is_valid() and formset.is_valid()
  • 编辑现有父对象时传递
    instance
    参数

Pitfalls

常见陷阱

  • Validating in views instead of forms
  • Silently redirecting without checking
    is_valid()
  • Forgetting
    commit=False
    when setting related fields
  • Not displaying form errors to users
  • 在视图中而非表单中进行验证
  • 未检查
    is_valid()
    就直接重定向
  • 设置关联字段时忘记使用
    commit=False
  • 未向用户显示表单错误