• django表单的api


    django表单的api,参考文档:https://yiyibooks.cn/xx/Django_1.11.6/ref/forms/api.html

    绑定与未绑定形式:

    Form要么是绑定的,要么是未绑定的

    • 如果是绑定的,那么它能够验证数据,并渲染表单及其数据成HTML。
    • 如果未绑定,则无法进行验证(因为没有数据可以验证!),但它仍然可以以HTML形式呈现空白表单。

    我们有如下表单实例:

    from django import forms
    class UserInfo(forms.Form):
        username = forms.CharField(label=u"用户名", max_length=50)
        mobile = forms.CharField(label=u"手机号", max_length=20)
        subject = forms.CharField(label=u"主题", max_length=50)

    绑定一个表单

    >>> data = {"username":"jobs","mobile":"123456789", "subject":"Hello, World"}
    >>> user = UserInfo(data)     #把上面字典绑定到表单上。
    >>> user.is_bound             #检查表单是否绑定
    True

    >>> u1 = UserInfo({}) #即便传入的是一个空的字典,也会绑定
    >>> u1.is_bound
    True

    使用表单验证数据

    Form.clean()

    当你需要为相互依赖的字段添加自定义的验证时,你可以重写Formclean()方法。[...]

    Form.is_valid()

    Form对象的首要任务就是验证数据。 对于绑定的Form实例,可以调用is_valid()方法来执行验证,该方法会返回一个表示数据是否合法的布尔值。

    >>> user.is_valid()
    True

    >>> date = {"username":"jobs","mobile":123456789, "subject":" "} #把subject的值设为空。
    >>> u2 = UserInfo(date)
    >>> u2.is_valid()
    False
    Form.errors

    访问errors 属性可以获得错误信息的一个字典:

    >>> u2.errors
    {'subject': [u'This field is required.']}

    在这个字典中,键为字段的名称,值为表示错误信息的Unicode 字符串组成的列表。 错误信息保存在列表中是因为字段可能有多个错误信息。

    你可以在调用is_valid() 之前访问errors表单的数据将在第一次调用is_valid() 或者访问errors 时验证。

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

    有关错误信息还有几个方法如下,用到的时候再说明。

     Form.errors.as_data()
     Form.errors.as_json(escape_html=False) 
     Form.add_error(field, error)
     Form.has_error(字段,code = None)
     Form.non_field_errors()
    
    #地址

    动态初始值

    Form.initial

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

    使用Forminitial参数可以实现。 该参数是一个字典。 只包括您指定初始值的字段;没有必要在表单中包含每个字段。

    >>> u3 = UserInfo(initial={"username": "king"})
    >>> u3["username"]
    <django.forms.boundfield.BoundField object at 0x00000000046D6AC8>
    >>> u3["username"].value()
    'king'

    如果一个Field包含initial参数,并且你在实例化Form时又包含了一个initial参数,那么后一个initial优先级高。

    Form.get_initial_for_field(field,field_name)
    Django中的新功能1.11。

    使用get_initial_for_field()来检索表单字段的初始数据。 它以该顺序从Form.initialField.initial中检索数据,并评估任何可调用的初始值。

    Form.has_changed()

    当你需要检查表单的数据是否从初始数据发生改变时,(和初始数据比较发生变化)可以使用Form的has_changed()方法。

    >>> data = {"username":"king", "mobile":"123456789", "subject":"Fucking"}
    >>> f = UserInfo(data, initial=data)             #data是我们绑定的数据,initial是表示的初始的数据,当然这里是一样没有改变。
    >>> f.has_changed()
    False

    当提交表单时,我们可以重新构建表单并提供初始值,这样可以实现比较:

    >>> f = ContactForm(request.POST, initial=data)
    >>> f.has_changed()
    如果request.POST 中的数据与initial 中的不同,has_changed() 将为True,否则为False。 计算的结果是通过调用表单每个字段的Field.has_changed() 得到的。
    Form.changed_data

    changed_data属性返回一个列表,包含那些在表单的绑定数据中的值(通常为request.POST)与原始值发生改变的字段的名字。 如果没有数据不同,它返回一个空列表。

    >>> data1 = {"username":"king", "mobile":"123456789", "subject":"what a Fucking"}     #迷你更改
    >>> f2 = UserInfo(data1, initial=data)       
    >>> f2.has_changed()
    True
    >>> f2.changed_data
    ['subject']

    访问表单中的字段

    Form.fields

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

    >>> for item in f.fields:
    ...     print item
    ...     
    username
    mobile
    subject

    >>> f.fields["username"] #返回的是一个django.forms.fields.CharField 对象
    <django.forms.fields.CharField object at 0x00000000044B7080>

    访问干净的数据

    Form.cleaned_data

    Form类中的每个字段不仅负责验证数据,还负责“清洁”它们 —— 将它们转换为正确的格式。 这是个非常好用的功能,因为它允许字段以多种方式输入数据,并总能得到一致的输出。

    例如,DateField 将输入转换为Python 的 datetime.date 对象。 无论你传递的是DateField 格式的字符串、datetime.date 对象、还是其它格式的数字,'1994-07-15' 将始终将它们转换成datetime.date 对象,只要它们是合法的。

    一旦你创建一个Form实例并通过验证后,你就可以通过它的cleaned_data 属性访问清洁的数据:

    >>> f.is_valid()
    True
    >>> f.cleaned_data
    {'username': u'king', 'mobile': u'123456789', 'subject': u'Fucking'}

    #注意,文本字段 —— 例如,CharFieldEmailField —— 始终将输入转换为Unicode 字符串。

    如果你的数据没有 通过验证,cleaned_data 字典中只包含合法的字段:

    >>> data1
    {'username': 'king', 'mobile': '123456789', 'subject': ''}
    >>> f3 = UserInfo(data1)
    >>> f3.is_valid()
    False
    >>> f3.cleaned_data
    {'username': u'king', 'mobile': u'123456789'}

    cleaned_data 始终 包含Form中定义的字段,即使你在构建Form 时传递了额外的数据,cleaned_data也不会显示。

    Form合法时,cleaned_data 将包含所有字段的键和值,即使传递的数据不包含某些可选字段的值。

    >>> data2 = {'username': u'king', 'mobile': u'123456789'}           #我们需要4个字段的值,但是这里给出了三个
    >>> f3 = UserInfo(data2)
    >>> f3.is_valid()                                             #这里我自己测试的时候结果是False,但是官方文档给出的结果是True;
    False
    >>> f3.cleaned_data                                           #这个结果是一致的
    {'username': u'king', 'mobile': u'123456789'}

    输出表单为HTML

    我们知道表单本质就是html文档的展示,那么我们如何查看表单的html格式呢?

    >>> f4 = UserInfo()
    >>> print f4            #直接使用print打印实例化的实例即可,如果表单是绑定的输出的表单将会包含数据
    <tr><th><label for="id_username">用户名:</label></th><td><input id="id_username" maxlength="50" name="username" type="text" required /></td></tr>
    <tr><th><label for="id_mobile">手机号:</label></th><td><input id="id_mobile" maxlength="20" name="mobile" type="text" required /></td></tr>
    <tr><th><label for="id_subject">主题:</label></th><td><input id="id_subject" maxlength="50" name="subject" type="text" required /></td></tr>
    #查看每个表单的value属性。
    >>> print f3 <tr><th><label for="id_username">用户名:</label></th><td><input id="id_username" maxlength="50" name="username" type="text" value="king" required /></td></tr> <tr><th><label for="id_mobile">手机号:</label></th><td><input id="id_mobile" maxlength="20" name="mobile" type="text" value="123456789" required /></td></tr> <tr><th><label for="id_subject">主题:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input id="id_subject" maxlength="50" name="subject" type="text" required /></td></tr>
    默认的输出时具有两个列的HTML 表格,每个字段对应一个<tr>。 注意事项:
    
        为了灵活性,输出不包含</table> 和<table>、</form> 和<form> 以及<input type="submit"> 标签。 你需要添加它们。
        每个字段类型都有一个默认的HTML表示。 CharField is represented by an <input type="text"> and EmailField by an <input type="email">. BooleanField 
    表示为一个<input type="checkbox">。 注意,这些只是默认的表示;你可以使用Widget 指定字段使用哪种HTML,我们将稍后解释。 每个标签的HTML name 直接从ContactForm 类中获取。 每个字段的文本标签 —— 例如'Message:''Subject:''Cc myself:' 通过将所有的下划线转换成空格并大写第一个字母生成。 再次注意,这些只是明智的违约;您也可以手动指定标签。 每个文本标签周围有一个HTML <label> 标签,它指向表单字段的id。 这个id,是通过在字段名称前面加上'id_' 前缀生成。 id 属性和<label> 标签默认包含在输出中,但你可以改变这一行为。 输出使用HTML5语法,目标是&lt;!DOCTYPE html&gt;。 例如,它使用布尔属性,如checked,而不是checked='checked'的XHTML样式。
    Form.as_p()

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

    Form.as_ul()

    <li> 渲染表单为一系列的<li>标签,每个as_ul() 标签包含一个字段。 包含</ul><ul>,所以你可以自己指定<ul> 的任何HTML 属性:

    Form. as_table >()

    最后,as_table()输出表单为一个HTML <table>它与print 完全相同。 事实上,当你print 一个表单对象时,在后台调用的就是as_table() 方法:

    >>> f4.as_p()        #注意这里,返回的是一个unicode字段。
    u'<p><label for="id_username">u7528u6237u540d:</label> <input id="id_username" maxlength="50" name="username" type="text" required /></p>
    <p><label for="id_mobile">u624bu673au53f7:</label> <input id="id_mobile" maxlength="20" name="mobile" type="text" required /></p>
    <p><label for="id_subject">u4e3bu9898:</label> <input id="id_subject" maxlength="50" name="subject" type="text" required /></p>'
    >>> print f4.as_p()
    <p><label for="id_username">用户名:</label> <input id="id_username" maxlength="50" name="username" type="text" required /></p>
    <p><label for="id_mobile">手机号:</label> <input id="id_mobile" maxlength="20" name="mobile" type="text" required /></p>
    <p><label for="id_subject">主题:</label> <input id="id_subject" maxlength="50" name="subject" type="text" required /></p>

    设置特殊提示

    必填的表单和有错误的表单很常见,可以单独为其定义CSS样式。django有两个钩子,可以根据需求添加对应的属性。【把官网实例放这里】

    Form.error_css_classForm.required_css_class属性就是做这个用的:

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

    属性名是固定的,不可变(废话),通过赋值不同的字符串,表示给这两类属性添加不同的CSS的class属性。以后Django在渲染form成HTML时将自动为error和required行添加对应的CSS样式。

    上面的例子,其HTML看上去将类似:

    >>> f = ContactForm(data)
    >>> print(f.as_table())
    <tr class="required"><th><label class="required" for="id_subject">Subject:</label>    ...
    <tr class="required"><th><label class="required" for="id_message">Message:</label>    ...
    <tr class="required error"><th><label class="required" for="id_sender">Sender:</label>      ...
    <tr><th><label for="id_cc_myself">Cc myself:<label> ...
    >>> f['subject'].label_tag()
    <label class="required" for="id_subject">Subject:</label>
    >>> f['subject'].label_tag(attrs={'class': 'foo'})
    <label for="id_subject" class="foo required">Subject:</label>

    django表单的api还有很多,暂时先列到这里,再续!

  • 相关阅读:
    setup slack检查
    关于derive_pll_clock
    STA中的postmap和postfit
    sdc中对I/O口的约束set_input/output_delay
    hold slack的计算
    DDR I 和DDR II的简单比较
    ORA00600: 内部错误代码,参数: [kcratr1_lostwrt], [], [], [], [], [], [], []
    linux解压超过2G大文件
    linux 安装apache2.2.4
    plsql developer导出csv乱码问题
  • 原文地址:https://www.cnblogs.com/wxzhe/p/10319706.html
Copyright © 2020-2023  润新知