表单 API

    本文档介绍了 Django 的表单 API 的具体细节。你应该先阅读 。

    一个 Form 实例要么是 绑定 到一组数据,要么是 未绑定

    • 如果是 绑定 了一组数据,它就能够验证这些数据,并将表单渲染成 HTML,并在 HTML 中显示数据。
    • 如果是 未绑定,它就不能进行验证(因为没有数据可验证!),但它仍然可以将空白表单渲染为 HTML。

    class Form

    要创建一个未绑定的 实例,实例化类:

    要将数据绑定到表单中,将数据以字典的形式传递给你的 Form 类构造函数的第一个参数:

    1. >>> data = {'subject': 'hello',
    2. ... 'message': 'Hi there',
    3. ... 'sender': 'foo@example.com',
    4. ... 'cc_myself': True}
    5. >>> f = ContactForm(data)

    在这个字典中,键是字段名,对应于 类中的属性。值是你要验证的数据。这些数据通常是字符串,但不要求它们是字符串;你传递的数据类型取决于 Field,我们稍后会看到。

    Form.``is_bound

    如果你需要在运行时区分绑定和未绑定的表单实例,请检查表单的 属性的值:

    1. >>> f = ContactForm()
    2. >>> f.is_bound
    3. False
    4. >>> f = ContactForm({'subject': 'hello'})
    5. >>> f.is_bound
    6. True

    需要注意的是,传递一个空的字典会创建一个空数据的 绑定 表单:

    1. >>> f = ContactForm({})
    2. >>> f.is_bound
    3. True

    如果你有一个绑定的 Form 实例,并想以某种方式改变数据,或者你想将一个未绑定的 实例绑定到一些数据,请创建另一个 Form 实例。没有办法改变一个 实例中的数据。一旦创建了一个 Form 实例,你应该认为它的数据是不可改变的,不管它是否有数据。

    使用表单来验证数据

    Form.``clean()

    当你必须为相互依赖的字段添加自定义验证时,在你的 Form 上实现一个 clean() 方法。参见 的用法示例。

    Form.``is_valid()

    Form 对象的主要任务是验证数据。有了一个绑定的 实例,调用 is_valid() 方法来运行验证,并返回一个布尔值,指定数据是否有效:

    1. >>> data = {'subject': 'hello',
    2. ... 'message': 'Hi there',
    3. ... 'sender': 'foo@example.com',
    4. ... 'cc_myself': True}
    5. >>> f = ContactForm(data)
    6. >>> f.is_valid()
    7. True

    让我们用一些无效的数据试试。在这种情况下,subject 是空白的(这是一个错误,因为所有的字段都是默认的),sender 不是一个有效的电子邮件地址:

    1. >>> data = {'subject': '',
    2. ... 'message': 'Hi there',
    3. ... 'sender': 'invalid email address',
    4. ... 'cc_myself': True}
    5. >>> f = ContactForm(data)
    6. >>> f.is_valid()
    7. False

    Form.``errors

    访问 属性来获取错误信息的字典:

    1. >>> f.errors
    2. {'sender': ['Enter a valid email address.'], 'subject': ['This field is required.']}

    在这个字典中,键是字段名,值是代表错误信息的字符串列表。错误信息存储在列表中,因为一个字段可以有多个错误信息。

    你可以访问 errors,而不必先调用 。无论是调用 is_valid() 还是访问 ,表单的数据都会首先被验证。

    验证例程只会被调用一次,无论你访问 errors 或调用 多少次。这意味着,如果验证有副作用,这些副作用将只被触发一次。

    Form.errors.``as_data()

    返回一个 dict,将字段映射到它们的原始 ValidationError 实例。

    1. >>> f.errors.as_data()
    2. {'sender': [ValidationError(['Enter a valid email address.'])],
    3. 'subject': [ValidationError(['This field is required.'])]}

    当你需要通过错误 code 来识别错误时,请使用此方法。这样就可以在给定的错误出现时,重写错误信息或在视图中编写自定义逻辑。它还可以用来以自定义格式(如 XML)将错误序列化;例如, as_json() 依赖于 as_data()

    需要使用 as_data() 方法是由于向后兼容性。以前,ValidationError 实例一旦被添加到 Form.errors 字典中,其 渲染的 错误信息就会丢失。理想情况下,Form.errors 会存储 ValidationError 实例,并且带有 as_ 前缀的方法可以渲染它们,但为了不破坏那些期望在 Form.errors 中渲染错误信息的代码,必须反过来做。

    Form.errors.``as_json(escape_html=False)

    返回以 JSON 格式序列化的错误。

    1. >>> f.errors.as_json()
    2. {"sender": [{"message": "Enter a valid email address.", "code": "invalid"}],
    3. "subject": [{"message": "This field is required.", "code": "required"}]}

    默认情况下,as_json() 不会转义其输出。如果你使用它来处理类似 AJAX 请求的表单视图,客户端解释响应并将错误插入到页面中,你会希望确保在客户端转义结果,以避免跨站点脚本攻击的可能性。你可以在 JavaScript 中使用 element.textContent = errorText 或者使用 jQuery 的 $(el).text(errorText) (而不是它的 .html() 函数)来实现。

    如果出于某些原因你不想使用客户端转义,你也可以设置 escape_html=True,错误信息将被转义,这样你就可以直接在 HTML 中使用它们。

    Form.errors.``get_json_data(escape_html=False)

    Form. errors.as_json() 将返回序列化的 JSON,而这个则是返回序列化之前的错误数据。

    escape_html 参数的行为如 Form.errors.as_json() 中所述。

    Form.``add_error(field, error)

    该方法允许在 Form.clean() 方法中添加错误到特定字段,或者从表单外部添加错误,例如从视图中添加。

    field 参数是应该添加错误的字段名。如果它的值是 None,错误将被视为非字段错误,就像 返回的那样。

    error 参数可以是一个字符串,或者最好是 ValidationError 的实例。关于定义表单错误的最佳做法,请参见 引发 ValidationError

    注意,Form.add_error() 会自动从 cleaned_data 中删除相关字段。

    Form.``has_error(field, code=None)

    本方法返回一个布尔值,表示一个字段是否有特定错误 code 的错误。如果 codeNone,如果字段包含任何错误,它将返回 True

    要检查非字段错误,使用 作为 field 参数。

    Form.``non_field_errors()

    这个方法从 Form.errors 中返回没有与特定字段关联的错误列表。这包括在 中引发的 ValidationError 和使用 Form.add_error(None, "...") 添加的错误。

    在没有数据的情况下验证表单是没有意义的,但是,记录一下,以下是未绑定表单的情况:

    1. >>> f = ContactForm()
    2. >>> f.is_valid()
    3. False
    4. >>> f.errors
    5. {}

    动态初始值

    Form.``initial

    使用 在运行时声明表单字段的初始值。例如,你可能想用当前会话的用户名来填写 username 字段。

    要实现这一目标,请使用 initial 参数到 。如果给定这个参数,它应该是一个将字段名映射到初始值的字典。只包含你要指定初始值的字段,没有必要包含表单中的每个字段。例如:

    1. >>> f = ContactForm(initial={'subject': 'Hi there!'})

    这些值只对未绑定的表单显示,如果没有提供特定的值,它们不会被用作后备值。

    如果一个 Field 定义了 并且 你在实例化 Form 时包含了 initial,那么后者 initial 将具有优先权。在这个例子中,initial 既在字段级别又在表单实例级别提供,后者具有优先权:

    1. >>> from django import forms
    2. >>> class CommentForm(forms.Form):
    3. ... name = forms.CharField(initial='class')
    4. ... url = forms.URLField()
    5. ... comment = forms.CharField()
    6. >>> f = CommentForm(initial={'name': 'instance'}, auto_id=False)
    7. >>> print(f)
    8. <tr><th>Name:</th><td><input type="text" name="name" value="instance" required></td></tr>
    9. <tr><th>Url:</th><td><input type="url" name="url" required></td></tr>
    10. <tr><th>Comment:</th><td><input type="text" name="comment" required></td></tr>

    Form.``get_initial_for_field(field, field_name)

    使用 来获取表单字段的初始数据。它按顺序从 Form.initial 和 中获取数据,并执行任何可调用的初始值。

    检查哪些表格数据已经改变

    Form.``has_changed()

    当你需要检查表单数据是否与初始数据发生变化时,请使用 has_changed() 方法。

    1. >>> data = {'subject': 'hello',
    2. ... 'message': 'Hi there',
    3. ... 'sender': 'foo@example.com',
    4. ... 'cc_myself': True}
    5. >>> f = ContactForm(data, initial=data)
    6. >>> f.has_changed()
    7. False

    当表单提交后,我们会重新构建表单,并提供原始数据,以便进行对比。

    1. >>> f = ContactForm(request.POST, initial=data)
    2. >>> f.has_changed()

    如果来自 request.POST 的数据与 initial 中提供的数据不同,那么 has_changed() 将为 True,否则为 False。结果是通过调用 对表单中的每个字段进行计算。

    Form.``changed_data

    changed_data 属性返回表单绑定数据(通常是 request.POST)中与 initial 中提供的数据不同的字段名列表。如果没有不同的数据,则返回一个空列表。

    1. >>> f = ContactForm(request.POST, initial=data)
    2. >>> if f.has_changed():
    3. ... print("The following fields changed: %s" % ", ".join(f.changed_data))
    4. >>> f.changed_data
    5. ['subject', 'message']

    Form.``fields

    你可以从 实例的 fields 属性中访问其字段:

    1. >>> for row in f.fields.values(): print(row)
    2. ...
    3. <django.forms.fields.CharField object at 0x7ffaac632510>
    4. <django.forms.fields.URLField object at 0x7ffaac632f90>
    5. <django.forms.fields.CharField object at 0x7ffaac3aa050>
    6. >>> f.fields['name']
    7. <django.forms.fields.CharField object at 0x7ffaac6324d0>

    你可以改变 Form 实例的字段,以改变它在表单中的显示方式:

    1. >>> f.as_table().split('\n')[0]
    2. '<tr><th>Name:</th><td><input name="name" type="text" value="instance" required></td></tr>'
    3. >>> f.fields['name'].label = "Username"
    4. >>> f.as_table().split('\n')[0]
    5. '<tr><th>Username:</th><td><input name="name" type="text" value="instance" required></td></tr>'

    请注意不要修改 base_fields 属性,因为这个修改会影响同一 Python 进程中所有后续的 ContactForm 实例:

    1. >>> f.base_fields['name'].label = "Username"
    2. >>> another_f = CommentForm(auto_id=False)
    3. >>> another_f.as_table().split('\n')[0]
    4. '<tr><th>Username:</th><td><input name="name" type="text" value="class" required></td></tr>'

    访问“干净的”数据

    Form.``cleaned_data

    类中的每个字段不仅负责验证数据,还负责“清理”数据——将其规范为一致的格式。这是一个很好的功能,因为它允许以各种方式输入特定字段的数据,并总是产生一致的输出。

    当你用一组数据创建了一个 Form 实例并对其进行验证后,你就可以通过它的 cleaned_data 属性来访问干净的数据:

    1. >>> data = {'subject': 'hello',
    2. ... 'message': 'Hi there',
    3. ... 'sender': 'foo@example.com',
    4. ... 'cc_myself': True}
    5. >>> f = ContactForm(data)
    6. >>> f.is_valid()
    7. True
    8. >>> f.cleaned_data
    9. {'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}

    请注意,任何基于文本的字段——如 CharFieldEmailField——总是将输入清理成一个字符串。我们将在本文档后面介绍编码的含义。

    如果你的数据 没有 验证,cleaned_data 字典只包含有效字段:

    1. >>> data = {'subject': '',
    2. ... 'message': 'Hi there',
    3. ... 'sender': 'invalid email address',
    4. ... 'cc_myself': True}
    5. >>> f = ContactForm(data)
    6. >>> f.is_valid()
    7. False
    8. >>> f.cleaned_data
    9. {'cc_myself': True, 'message': 'Hi there'}

    cleaned_data 总是只包含 Form 中定义的字段的键,即使你在定义 Form 时传递了额外的数据。在这个例子中,我们传递了一堆额外的字段给 ContactForm 构造函数,但是 cleaned_data 只包含了表单的字段:

    1. >>> data = {'subject': 'hello',
    2. ... 'message': 'Hi there',
    3. ... 'sender': 'foo@example.com',
    4. ... 'cc_myself': True,
    5. ... 'extra_field_1': 'foo',
    6. ... 'extra_field_2': 'bar',
    7. ... 'extra_field_3': 'baz'}
    8. >>> f = ContactForm(data)
    9. >>> f.is_valid()
    10. True
    11. >>> f.cleaned_data # Doesn't contain extra_field_1, etc.
    12. {'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}

    Form 有效时,cleaned_data 将包括 所有 字段的键和值,即使数据没有包括一些可选字段的值。在这个例子中,数据字典没有包含 nick_name 字段的值,但 cleaned_data 包含了它,并使用一个空值:

    在上面这个例子中,nick_namecleaned_data 值被设置为一个空字符串,因为 nick_nameCharField,而 CharField 将空值视为空字符串。每个字段类型都知道它的“空”值是什么——例如,对于 DateField,它是 None 而不是空字符串。关于每个字段在这种情况下的行为的全部细节,请参阅下面“内置 Field 类”一节中每个字段的“空值”说明。

    你可以编写代码来对特定的表单字段(基于其名称)或整个表单(考虑各种字段的组合)进行验证。更多关于这方面的信息请参见 。

    将表单输出为 HTML

    Form 对象的第二个任务是将其本身渲染为 HTML。为此,print 对象:

    1. >>> f = ContactForm()
    2. >>> print(f)
    3. <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr>
    4. <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr>
    5. <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr>
    6. <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr>

    如果表单与数据绑定,HTML 输出将适当地包含该数据。例如,如果一个字段用 <input type="text"> 表示,数据将在 value 属性中。如果一个字段用 <input type="checkbox"> 表示,那么 HTML 将适当地包括 checked

    1. >>> data = {'subject': 'hello',
    2. ... 'message': 'Hi there',
    3. ... 'cc_myself': True}
    4. >>> f = ContactForm(data)
    5. >>> print(f)
    6. <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" value="Hi there" required></td></tr>
    7. <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" value="foo@example.com" required></td></tr>
    8. <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" checked></td></tr>

    这个默认输出是一个两列的 HTML 表单,每个字段都有一个 <tr>。请注意以下几点:

    • 为灵活起见,输出 包括 <table></table> 标签,也不包括 <form></form> 标签或 <input type="submit"> 标签。这是你的工作。
    • 每个字段类型都有一个默认的 HTML 表示。CharField<input type="text"> 表示,EmailField<input type="email"> 表示。BooleanField(null=False) 由一个 <input type="checkbox">。请注意,这些只是合理的默认值;你可以通过使用部件来指定一个给定字段使用的 HTML,我们将在后面解释。
    • 每个标签的 HTML name 直接从 ContactForm 类中的属性名中提取。
    • 每个字段的文本标签——例如 'Subject:''Message:''Cc myself:',是根据字段名将所有下划线转换为空格并将第一个字母大写而产生的。同样,请注意这些只是合理的默认值;你也可以手动指定标签。
    • 每个文本标签都被一个 HTML <label> 标签包围,该标签通过其 id 指向相应的表格字段。而它的 id 则是通过在字段名前加上 'id_' 生成的。id 属性和 <label> 标签默认包含在输出中,以遵循最佳实践,但你可以改变这种行为。
    • 输出使用 HTML5 语法,目标是 <!DOCTYPE html>。例如,它使用布尔属性,如 checked 而不是 XHTML 风格的 checked='checked'

    虽然当你 print 表单时,<table> 输出是默认的输出样式,但还有其他的输出样式。每种样式都可以作为表单对象的一个方法,每个渲染方法都返回一个字符串。

    as_p()

    Form.``as_p()

    as_p() 将表单渲染为一系列 <p> 标签,每个 <p> 包含一个字段:

    1. >>> f = ContactForm()
    2. >>> f.as_p()
    3. '<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></p>\n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></p>\n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" required></p>\n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></p>'
    4. >>> print(f.as_p())
    5. <p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></p>
    6. <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></p>
    7. <p><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></p>
    8. <p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></p>

    as_ul()

    Form.``as_ul()

    as_ul() 将表单渲染为一系列 <li> 标签,每个 <li> 包含一个字段。它并 包括 <ul></ul>,因此你可以在 <ul> 上指定任何 HTML 属性,以提高灵活性:

    1. >>> f = ContactForm()
    2. >>> f.as_ul()
    3. '<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></li>\n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></li>\n<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></li>\n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></li>'
    4. >>> print(f.as_ul())
    5. <li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" required></li>
    6. <li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" required></li>
    7. <li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" required></li>
    8. <li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself"></li>

    as_table()

    Form.``as_table()

    最后,as_table() 将表单输出为 HTML <table>。这和 print 完全一样。事实上,当你 print 一个表单对象时,它在幕后调用了它的 as_table() 方法:

    1. >>> f = ContactForm()
    2. >>> f.as_table()
    3. '<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr>\n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr>\n<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr>'
    4. >>> print(f)
    5. <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" required></td></tr>
    6. <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" required></td></tr>
    7. <tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" required></td></tr>
    8. <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself"></td></tr>

    Form.``error_css_class

    Form.``required_css_class

    对必填或有错误的表单行和字段进行样式设计是很常见的。例如,你可能想用粗体显示必填的表格行,用红色突出显示错误。

    Form 类有几个钩子,你可以用来给必填行或有错误的行添加 class 属性:设置 和/或 Form.required_css_class 属性:

    1. from django import forms
    2. class ContactForm(forms.Form):
    3. error_css_class = 'error'
    4. required_css_class = 'required'
    5. # ... and the rest of your fields here

    一旦你这样做了,根据需要,行将被赋予 "error" 和/或 "required" 类。HTML 将看起来像:

    1. >>> f = ContactForm(data)
    2. >>> print(f.as_table())
    3. <tr class="required"><th><label class="required" for="id_subject">Subject:</label> ...
    4. <tr class="required"><th><label class="required" for="id_message">Message:</label> ...
    5. <tr class="required error"><th><label class="required" for="id_sender">Sender:</label> ...
    6. <tr><th><label for="id_cc_myself">Cc myself:<label> ...
    7. >>> f['subject'].label_tag()
    8. <label class="required" for="id_subject">Subject:</label>
    9. >>> f['subject'].label_tag(attrs={'class': 'foo'})
    10. <label for="id_subject" class="foo required">Subject:</label>

    设置表单元素的 HTML id 属性和 <label> 标签。

    Form.``auto_id

    默认情况下,表单渲染方法包括:

    • 表单元素的 HTML id 属性。
    • 标签周围对应的 <label> 标签。HTML <label> 标签指定了哪个标签文本与哪个表单元素相关联。这个小小的改进使表单更加可用,也更容易被辅助设备访问。使用 <label> 标签总是一个好主意。

    id 属性值是通过将 id_ 预置到表单字段名后生成的。 如果你想改变 id 惯例或完全删除 HTML id 属性和 <label> 标签,这种行为是可以设置的。

    使用 Form 构造函数的 auto_id 参数来控制 id 和标签行为。这个参数必须是 TrueFalse 或一个字符串。

    如果 auto_idFalse,那么表单输出将不包含 <label> 标签或 id 属性:

    1. >>> f = ContactForm(auto_id=False)
    2. >>> print(f.as_table())
    3. <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" required></td></tr>
    4. <tr><th>Message:</th><td><input type="text" name="message" required></td></tr>
    5. <tr><th>Sender:</th><td><input type="email" name="sender" required></td></tr>
    6. <tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself"></td></tr>
    7. >>> print(f.as_ul())
    8. <li>Subject: <input type="text" name="subject" maxlength="100" required></li>
    9. <li>Message: <input type="text" name="message" required></li>
    10. <li>Sender: <input type="email" name="sender" required></li>
    11. <li>Cc myself: <input type="checkbox" name="cc_myself"></li>
    12. >>> print(f.as_p())
    13. <p>Subject: <input type="text" name="subject" maxlength="100" required></p>
    14. <p>Message: <input type="text" name="message" required></p>
    15. <p>Sender: <input type="email" name="sender" required></p>
    16. <p>Cc myself: <input type="checkbox" name="cc_myself"></p>

    如果 auto_id 设置为 True,那么表单输出 包括 <label> 标签,并将使用字段名作为每个表单字段的 id

    1. >>> f = ContactForm(auto_id=True)
    2. >>> print(f.as_table())
    3. <tr><th><label for="subject">Subject:</label></th><td><input id="subject" type="text" name="subject" maxlength="100" required></td></tr>
    4. <tr><th><label for="message">Message:</label></th><td><input type="text" name="message" id="message" required></td></tr>
    5. <tr><th><label for="sender">Sender:</label></th><td><input type="email" name="sender" id="sender" required></td></tr>
    6. <tr><th><label for="cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="cc_myself"></td></tr>
    7. >>> print(f.as_ul())
    8. <li><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" required></li>
    9. <li><label for="message">Message:</label> <input type="text" name="message" id="message" required></li>
    10. <li><label for="sender">Sender:</label> <input type="email" name="sender" id="sender" required></li>
    11. <li><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself"></li>
    12. >>> print(f.as_p())
    13. <p><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" required></p>
    14. <p><label for="message">Message:</label> <input type="text" name="message" id="message" required></p>
    15. <p><label for="sender">Sender:</label> <input type="email" name="sender" id="sender" required></p>
    16. <p><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself"></p>

    如果 auto_id 被设置为包含格式字符 '%s' 的字符串,那么表单输出将包含 <label> 标签,并将根据格式字符串生成 id 属性。例如,对于格式字符串 'field_%s',名为 subject 的字段将得到 id'field_subject'。继续我们的例子:

    1. >>> f = ContactForm(auto_id='id_for_%s')
    2. >>> print(f.as_table())
    3. <tr><th><label for="id_for_subject">Subject:</label></th><td><input id="id_for_subject" type="text" name="subject" maxlength="100" required></td></tr>
    4. <tr><th><label for="id_for_message">Message:</label></th><td><input type="text" name="message" id="id_for_message" required></td></tr>
    5. <tr><th><label for="id_for_sender">Sender:</label></th><td><input type="email" name="sender" id="id_for_sender" required></td></tr>
    6. <tr><th><label for="id_for_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_for_cc_myself"></td></tr>
    7. >>> print(f.as_ul())
    8. <li><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" required></li>
    9. <li><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" required></li>
    10. <li><label for="id_for_sender">Sender:</label> <input type="email" name="sender" id="id_for_sender" required></li>
    11. <li><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself"></li>
    12. >>> print(f.as_p())
    13. <p><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" required></p>
    14. <p><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" required></p>
    15. <p><label for="id_for_sender">Sender:</label> <input type="email" name="sender" id="id_for_sender" required></p>
    16. <p><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself"></p>

    如果 auto_id 被设置为任何其他的真值——比如一个不包含 %s 的字符串——那么该库就会像 auto_idTrue 一样。

    默认情况下,auto_id 被设置为字符串 'id_%s'

    Form.``label_suffix

    一个可翻译的字符串(英文默认为冒号(:)),将在渲染表格时附加在任何标签名称之后。

    可以使用 label_suffix 参数自定义该字符,或者完全省略:

    1. >>> f = ContactForm(auto_id='id_for_%s', label_suffix='')
    2. >>> print(f.as_ul())
    3. <li><label for="id_for_subject">Subject</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" required></li>
    4. <li><label for="id_for_message">Message</label> <input type="text" name="message" id="id_for_message" required></li>
    5. <li><label for="id_for_sender">Sender</label> <input type="email" name="sender" id="id_for_sender" required></li>
    6. <li><label for="id_for_cc_myself">Cc myself</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself"></li>
    7. >>> f = ContactForm(auto_id='id_for_%s', label_suffix=' ->')
    8. >>> print(f.as_ul())
    9. <li><label for="id_for_subject">Subject -></label> <input id="id_for_subject" type="text" name="subject" maxlength="100" required></li>
    10. <li><label for="id_for_message">Message -></label> <input type="text" name="message" id="id_for_message" required></li>
    11. <li><label for="id_for_sender">Sender -></label> <input type="email" name="sender" id="id_for_sender" required></li>
    12. <li><label for="id_for_cc_myself">Cc myself -></label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself"></li>

    请注意,只有当标签的最后一个字符不是标点符号时,才会加上标签后缀(在英文中,这些字符是 .!?:)。

    字段也可以定义自己的 。这将优先于 Form.label_suffix。后缀也可以在运行时使用 label_suffix() 参数来覆盖。

    Form.``use_required_attribute

    当设置为 True (默认)时,必填表单字段将有 required HTML 属性。

    实例化表单时使用 use_required_attribute=False 以避免从表单集中添加和删除表单时浏览器验证错误。

    设置表单组件的渲染方式

    Form.``default_renderer

    指定 渲染器 用于表单的渲染。默认值为 None,表示使用 设置中指定的默认渲染器。

    你可以在声明你的表单时将其设置为一个类属性,或者使用 Form.__init__()renderer 参数。例如:

    1. from django import forms
    2. class MyForm(forms.Form):
    3. default_renderer = MyRenderer()

    或者:

    1. form = MyForm(renderer=MyRenderer())

    字段顺序的注意事项

    as_p()as_ul()as_table() 快捷方式中,字段是按照你在表单类中定义的顺序显示的。例如,在 ContactForm 的例子中,字段是按照 subjectmessagesendercc_myself 的顺序定义的。要调整 HTML 输出的顺序,改变这些字段在类中的排列顺序。

    还有其他几种方式可以自定义顺序:

    Form.``field_order

    默认情况下 Form.field_order=None,它保留了你在表单类中定义字段的顺序。如果 field_order 是一个字段名的列表,则字段按列表指定的顺序排列,其余字段按默认顺序追加。列表中未知的字段名将被忽略。这使得在子类中可以通过将字段设置为 None 来禁用字段,而不必重新定义排序。

    你也可以使用 FormForm.field_order 参数来覆盖字段顺序。如果一个 定义了 field_order并且 你在实例化 Form 时包含了 field_order,那么后者的 field_order 将具有优先权。

    Form.``order_fields(field_order)

    你可以在任何时候使用 order_fields() 对字段进行重新排列,字段名列表如 。

    如果你渲染一个绑定的 Form 对象,渲染行为将自动运行表单的验证,如果它还没有发生,HTML 输出将包括验证错误,作为字段附近的 <ul class="errorlist">。错误信息的具体位置取决于你使用的输出方法:

    1. >>> data = {'subject': '',
    2. ... 'message': 'Hi there',
    3. ... 'sender': 'invalid email address',
    4. ... 'cc_myself': True}
    5. >>> f = ContactForm(data, auto_id=False)
    6. >>> print(f.as_table())
    7. <tr><th>Subject:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" required></td></tr>
    8. <tr><th>Message:</th><td><input type="text" name="message" value="Hi there" required></td></tr>
    9. <tr><th>Sender:</th><td><ul class="errorlist"><li>Enter a valid email address.</li></ul><input type="email" name="sender" value="invalid email address" required></td></tr>
    10. <tr><th>Cc myself:</th><td><input checked type="checkbox" name="cc_myself"></td></tr>
    11. >>> print(f.as_ul())
    12. <li><ul class="errorlist"><li>This field is required.</li></ul>Subject: <input type="text" name="subject" maxlength="100" required></li>
    13. <li>Message: <input type="text" name="message" value="Hi there" required></li>
    14. <li><ul class="errorlist"><li>Enter a valid email address.</li></ul>Sender: <input type="email" name="sender" value="invalid email address" required></li>
    15. <li>Cc myself: <input checked type="checkbox" name="cc_myself"></li>
    16. >>> print(f.as_p())
    17. <p><ul class="errorlist"><li>This field is required.</li></ul></p>
    18. <p>Subject: <input type="text" name="subject" maxlength="100" required></p>
    19. <p>Message: <input type="text" name="message" value="Hi there" required></p>
    20. <p>Sender: <input type="email" name="sender" value="invalid email address" required></p>
    21. <p>Cc myself: <input checked type="checkbox" name="cc_myself"></p>

    自定义错误列表格式

    默认情况下,表单使用 django.forms.utils.ErrorList 来格式化验证错误。如果你想使用一个替代的类来显示错误,你可以在构造时传入:

    1. >>> from django.forms.utils import ErrorList
    2. >>> class DivErrorList(ErrorList):
    3. ... def __str__(self):
    4. ... return self.as_divs()
    5. ... def as_divs(self):
    6. ... if not self: return ''
    7. ... return '<div class="errorlist">%s</div>' % ''.join(['<div class="error">%s</div>' % e for e in self])
    8. >>> f = ContactForm(data, auto_id=False, error_class=DivErrorList)
    9. >>> f.as_p()
    10. <div class="errorlist"><div class="error">This field is required.</div></div>
    11. <p>Subject: <input type="text" name="subject" maxlength="100" required></p>
    12. <p>Message: <input type="text" name="message" value="Hi there" required></p>
    13. <p>Sender: <input type="email" name="sender" value="invalid email address" required></p>
    14. <p>Cc myself: <input checked type="checkbox" name="cc_myself"></p>

    更精细的输出

    as_p()as_ul()as_table() 方法都是快捷方式——它们并不是显示表单对象的唯一方式。

    class BoundField

    用于显示 Form 实例的单个字段的 HTML 或访问属性。

    该对象的 __str__() 方法显示该字段的 HTML。

    要检索一个单一的 BoundField,在你的表单中使用字典查询语法,使用字段名作为键:

    1. >>> form = ContactForm()
    2. >>> print(form['subject'])
    3. <input id="id_subject" type="text" name="subject" maxlength="100" required>

    要检索所有的 BoundField 对象,请迭代表单:

    1. >>> form = ContactForm()
    2. >>> for boundfield in form: print(boundfield)
    3. <input id="id_subject" type="text" name="subject" maxlength="100" required>
    4. <input type="text" name="message" id="id_message" required>
    5. <input type="email" name="sender" id="id_sender" required>
    6. <input type="checkbox" name="cc_myself" id="id_cc_myself">

    特定字段的输出尊重表单对象的 auto_id 设置:

    1. >>> f = ContactForm(auto_id=False)
    2. >>> print(f['message'])
    3. <input type="text" name="message" required>
    4. >>> f = ContactForm(auto_id='id_%s')
    5. >>> print(f['message'])
    6. <input type="text" name="message" id="id_message" required>

    BoundField 的属性

    BoundField.``auto_id

    BoundField 的 HTML ID 属性。如果 是 False,则返回一个空字符串。

    此属性返回由部件的 value_from_datadict() 方法提取的此 的数据,如果没有给定则返回 None

    1. >>> unbound_form = ContactForm()
    2. >>> print(unbound_form['subject'].data)
    3. None
    4. >>> bound_form = ContactForm(data={'subject': 'My Subject'})
    5. >>> print(bound_form['subject'].data)
    6. My Subject

    BoundField.``errors

    一个 类似列表的对象,打印时显示为 HTML <ul class="errorlist">

    1. >>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''}
    2. >>> f = ContactForm(data, auto_id=False)
    3. >>> print(f['message'])
    4. <input type="text" name="message" required>
    5. >>> f['message'].errors
    6. ['This field is required.']
    7. >>> print(f['message'].errors)
    8. <ul class="errorlist"><li>This field is required.</li></ul>
    9. >>> f['subject'].errors
    10. []
    11. >>> print(f['subject'].errors)
    12. >>> str(f['subject'].errors)
    13. ''

    BoundField.``field

    这个 封装的表单类中的表单 BoundField 实例。

    BoundField.``form

    这个 实例与这个 BoundField 绑定。

    BoundField.``help_text

    字段的 。

    BoundField.``html_name

    部件的 HTML name 属性中使用的名称。它考虑到了 prefix 的形式。

    BoundField.``id_for_label

    使用这个属性来渲染这个字段的 ID。例如,如果你在你的模板中手动构建一个 <label> (尽管事实上 将为你做这件事):

    默认情况下,这将是字段的名称,前缀为 id_ (上面的例子为 “id_my_field“)。你可以通过设置 attrs 对字段的部件进行修改。例如,声明一个字段是这样的:

    1. my_field = forms.CharField(widget=forms.TextInput(attrs={'id': 'myFIELD'}))

    并使用上面的模板,会呈现出这样的效果:

    1. <label for="myFIELD">...</label><input id="myFIELD" type="text" name="my_field" required>

    BoundField.``is_hidden

    如果这个 的部件被隐藏,返回 True

    BoundField.``label

    字段的 label。这在 中使用。

    BoundField.``name

    表单中该字段的名称:

    1. >>> f = ContactForm()
    2. >>> print(f['subject'].name)
    3. subject
    4. >>> print(f['message'].name)
    5. message

    BoundField.``widget_type

    New in Django 3.1.

    返回包装字段的部件的小写类名,去掉后面的 inputwidget。当构建表单时,布局取决于组件的类型时,可以使用这个方法。例如:

    1. {% for field in form %}
    2. {% if field.widget_type == 'checkbox' %}
    3. # render one way
    4. {% else %}
    5. # render another way
    6. {% endif %}
    7. {% endfor %}

    BoundField 方法

    BoundField.``as_hidden(attrs=None, \*kwargs*)

    返回将其表示为 <input type="hidden"> 的 HTML 字符串。

    **kwargs 传递给 as_widget()

    这个方法主要在内部使用。你应该使用部件来代替。

    BoundField.``as_widget(widget=None, attrs=None, only_initial=False)

    通过渲染通过的部件来渲染该字段,并添加作为 attrs 传递的任何 HTML 属性。 如果没有指定部件,那么将使用该字段的默认部件。

    only_initial 是 Django 内部使用的,不应该明确设置。

    BoundField.``css_classes(extra_classes=None)

    当你使用 Django 的渲染快捷方式时,CSS 类被用来指示必填的表单字段或包含错误的字段。如果你是手动渲染表单,你可以使用 css_classes 方法访问这些 CSS 类:

    1. >>> f = ContactForm(data={'message': ''})
    2. >>> f['message'].css_classes()
    3. 'required'

    如果你想在可能需要的错误和必要的类之外提供一些额外的类,你可以提供这些类作为参数:

    1. >>> f = ContactForm(data={'message': ''})
    2. >>> f['message'].css_classes('foo bar')
    3. 'foo bar required'

    BoundField.``label_tag(contents=None, attrs=None, label_suffix=None)

    要单独呈现一个表单字段的标签,可以调用它的 label_tag() 方法:

    1. >>> f = ContactForm(data={'message': ''})
    2. >>> print(f['message'].label_tag())
    3. <label for="id_message">Message:</label>

    你可以提供 contents 参数,它将取代自动生成的标签标签。attrs 字典可以包含 <label> 标签的附加属性。

    生成的 HTML 包括表单的 (默认为冒号),如果设置了,则包括当前字段的 label_suffix。可选的 label_suffix 参数允许你覆盖任何先前设置的后缀。例如,你可以使用一个空字符串来隐藏选定字段的标签。如果你需要在模板中这样做,你可以写一个自定义过滤器来允许传递参数到 label_tag

    BoundField.``value()

    使用此方法渲染此字段的原始值,如同 Widget

    1. >>> initial = {'subject': 'welcome'}
    2. >>> unbound_form = ContactForm(initial=initial)
    3. >>> bound_form = ContactForm(data={'subject': 'hi'}, initial=initial)
    4. >>> print(unbound_form['subject'].value())
    5. welcome
    6. >>> print(bound_form['subject'].value())
    7. hi

    如果你需要访问模板中表单字段的一些附加信息,而使用 的子类还不够,也可以考虑自定义 BoundField

    自定义表单字段可以覆盖 get_bound_field()

    Field.``get_bound_field(form, field_name)

    取一个 的实例和字段名。当在模板中访问该字段时,将使用返回值。它很可能是 BoundField 的一个子类的实例。

    例如,如果你有一个 GPSCoordinatesField,并希望能够在模板中访问关于坐标的附加信息,可以按以下方式实现:

    1. class GPSCoordinatesBoundField(BoundField):
    2. @property
    3. def country(self):
    4. """
    5. Return the country the coordinates lie in or None if it can't be
    6. determined.
    7. """
    8. value = self.value()
    9. if value:
    10. return get_country_from_coordinates(value)
    11. else:
    12. return None
    13. class GPSCoordinatesField(Field):
    14. def get_bound_field(self, form, field_name):
    15. return GPSCoordinatesBoundField(form, self, field_name)

    现在你可以在模板中使用 {{form.coordinates.country }} 访问国家。

    将上传的文件绑定到表单中

    处理有 FileFieldImageField 字段的表单比普通表单要复杂一些。

    首先,为了上传文件,你需要确保你的 <form> 元素正确地将 enctype 定义为 "multipart/form-data"

    1. <form enctype="multipart/form-data" method="post" action="/foo/">

    其次,当你使用表单时,你需要绑定文件数据。文件数据与普通的表单数据是分开处理的,所以当你的表单包含一个 FileFieldImageField 时,你需要在绑定表单时指定第二个参数。因此,如果我们扩展我们的 ContactForm,包含一个名为 mugshotImageField,我们需要绑定包含 mugshot 图片的文件数据:

    1. # Bound form with an image field
    2. >>> from django.core.files.uploadedfile import SimpleUploadedFile
    3. >>> data = {'subject': 'hello',
    4. ... 'message': 'Hi there',
    5. ... 'sender': 'foo@example.com',
    6. ... 'cc_myself': True}
    7. >>> file_data = {'mugshot': SimpleUploadedFile('face.jpg', <file data>)}
    8. >>> f = ContactFormWithMugshot(data, file_data)

    在实践中,你通常会指定 request.FILES 作为文件数据的来源(就像你使用 request.POST 作为表单数据的来源一样):

    1. # Bound form with an image field, data from the request
    2. >>> f = ContactFormWithMugshot(request.POST, request.FILES)

    构造非绑定表单的方法和以往一样——省略表单数据 文件数据:

    1. # Unbound form with an image field
    2. >>> f = ContactFormWithMugshot()

    Form.``is_multipart()

    如果你正在编写可重用的视图或模板,你可能无法提前知道你的表单是否是一个多部分表单。is_multipart() 方法可以告诉你表单是否需要多部分编码来提交:

    1. >>> f = ContactFormWithMugshot()
    2. >>> f.is_multipart()
    3. True

    下面是一个如何在模板中使用的例子:

    1. {% if form.is_multipart %}
    2. <form enctype="multipart/form-data" method="post" action="/foo/">
    3. {% else %}
    4. <form method="post" action="/foo/">
    5. {% endif %}
    6. {{ form }}
    7. </form>

    子类化表单

    如果你有多个共享字段的 Form 类,你可以使用子类来消除冗余。

    当你将一个自定义的 Form 类子类化时,生成的子类将包括父类的所有字段,然后是你在子类中定义的字段。

    在这个例子中,ContactFormWithPriority 包含了 ContactForm 的所有字段,加上一个额外的字段 priorityContactForm 字段是按顺序排列的:

    1. >>> class ContactFormWithPriority(ContactForm):
    2. ... priority = forms.CharField()
    3. >>> f = ContactFormWithPriority(auto_id=False)
    4. >>> print(f.as_ul())
    5. <li>Subject: <input type="text" name="subject" maxlength="100" required></li>
    6. <li>Message: <input type="text" name="message" required></li>
    7. <li>Sender: <input type="email" name="sender" required></li>
    8. <li>Cc myself: <input type="checkbox" name="cc_myself"></li>
    9. <li>Priority: <input type="text" name="priority" required></li>

    可以对多个表单进行子类化,将表单视为混搭。在这个例子中,BeatleForm 同时对 PersonFormInstrumentForm 进行子类化(按顺序),它的字段列表包括父类的字段:

    1. >>> from django import forms
    2. >>> class PersonForm(forms.Form):
    3. ... first_name = forms.CharField()
    4. ... last_name = forms.CharField()
    5. >>> class InstrumentForm(forms.Form):
    6. ... instrument = forms.CharField()
    7. >>> class BeatleForm(InstrumentForm, PersonForm):
    8. ... haircut_type = forms.CharField()
    9. >>> b = BeatleForm(auto_id=False)
    10. >>> print(b.as_ul())
    11. <li>First name: <input type="text" name="first_name" required></li>
    12. <li>Last name: <input type="text" name="last_name" required></li>
    13. <li>Instrument: <input type="text" name="instrument" required></li>
    14. <li>Haircut type: <input type="text" name="haircut_type" required></li>

    可以通过在子类上将字段名称设置为 “None“ 来声明性地删除从父类继承的 Field。例如:

    1. >>> from django import forms
    2. >>> class ParentForm(forms.Form):
    3. ... name = forms.CharField()
    4. ... age = forms.IntegerField()
    5. >>> class ChildForm(ParentForm):
    6. ... name = None
    7. >>> list(ChildForm().fields)
    8. ['age']

    表单前缀

    Form.``prefix

    你可以在一个 <form> 标签中放入多个 Django 表单。

    1. >>> mother = PersonForm(prefix="mother")
    2. >>> father = PersonForm(prefix="father")
    3. >>> print(mother.as_ul())
    4. <li><label for="id_mother-first_name">First name:</label> <input type="text" name="mother-first_name" id="id_mother-first_name" required></li>
    5. <li><label for="id_mother-last_name">Last name:</label> <input type="text" name="mother-last_name" id="id_mother-last_name" required></li>
    6. >>> print(father.as_ul())
    7. <li><label for="id_father-first_name">First name:</label> <input type="text" name="father-first_name" id="id_father-first_name" required></li>
    8. <li><label for="id_father-last_name">Last name:</label> <input type="text" name="father-last_name" id="id_father-last_name" required></li>
    1. >>> class PersonForm(forms.Form):
    2. ... ...
    3. ... prefix = 'person'