verification kit form

1. The introduction of case

  • Implementation of the registration function
    • User names can not contain "FML", if the user input, you are prompted for illegal content
    • Password is at least six, or prompt for password is too short
  • Explanation
    • Check data are typically front and rear ends
    • Can not check the front end, a rear end, but the checksum must

2. form functional components

  • Rendering page: set up the front page
  • Verification data: acquiring data submitted by the user check the distal end
  • Display error: the verification result is returned to the front end of the data displayed to the user

3. form assembly using

3.1 custom form validation class

# views.py
from django import forms


class MyForm(forms.Form):
    username = forms.CharField(min_length=4, max_length=16)
    password = forms.CharField(min_length=6, max_length=16)
    email = forms.EmailField()

3.2 check data

  • Check the legitimacy of data
from app01 import views

# 将要校验的数据以字典的形式传给自定义的类
obj = views.MyForm({'username': 'qwer', 'password': '1234','email': 'ema'})

# 判断数据是否合法
print(obj.is_vaild())       # 所有数据都负荷要求才返回True

# 查看符合校验条件的数据
print(obj.clean_data)       # 此处username符合

# 查看不符合校验条件的数据
print(obj.errors)
# 此处password与email不符合,结果如下
{
    'password':['Ensure this value has at least 6 characters (it has 4).'],
    'email': ['Enter a valid email address.']
}
  • Multi-pass transmission values ​​less the case when parity data
from app01 import views

# 少传值的情况
obj = views.MyForm({'username': 'qwer', 'password': '123456'})
print(obj.is_vaild)     # False
print(obj.errors)       # {'email': ['This field is required.']}

# 多传值的情况
obj = views.MyForm({'username': 'qwer', 'password': '123456', 'email': '[email protected]', 'abc': '123'})
print(obj.is_vaild)     # True
  • Explanation

    By default, you can multi-pass value, but must not be less Biography

3.3 Rendering page

  • forms will only render the component label to obtain user input, need to manually write the submit button
  • Three rendering the front page of the way
{# 第一种:封装程度太高,标签参数不方便调整,可扩展性差(不推荐) #}
{{ form_obj.as_p }}
{{ form_obj.as_ul }}

{# 第二种:可扩展性高,但手写的代码较多,不推荐 #}
<p>
    {{ form_obj.username.label }}{{ form_obj.username }}
</p>
<p>
    {{ form_obj.password.label }}{{ form_obj.password }}
</p>
<p>
    {{ form_obj.email.label }}{{ form_obj.email }}
</p>

{# 第三种:可拓展性高,代码简洁,推荐使用 #}
{% for foo in for_obj %}
<p>
    {{ foo.label }}{{ foo }}
</p>
{% endfor %}

3.4 display an error message

  • Cancel distal verification method
{# 如果我们使用了form组件,前端就会帮我们做校验,但是我们不想使用前端校验 #}
{# 在for标签中添加novaildate #}
<form action='' method='post' novalidate></form>
  • Display error messages
{# 对象.errors.0 #}
<form action='' method='post' novalidate>
    {% for foo in form_obj %}
    <p>
        {{ foo.label }}{{ foo }}
        <span style='color:red'>{{ foo.errors.0 }}</span>
    </p>
    {% endfor %}
    
    <input type='submit'>
</form>

3.5 custom check result

  • Modify the error message in the error_messages
    • Enter empty error message: required
    • E-mail format error message: invalid
  • Review name label: label = 'username'
  • Setting an initial value: initial = 'initial value'
  • This can be empty: required = False
from django import forms

class MyForm(forms.Form):
    username = forms.CharField(min_length=4, max_length=16, label='用户名', 
                               error_messages={
                                   'min_length': '用户名最短4位',
                                   'max_length': '用户名最多16位',
                                   'required': '用户名不能为空',
                               },
                               initial='初始值'
                               )
    password = forms.CharField(min_length=6, max_length=16, label='密码',
                              error_messages={
                                  'min_length': '密码最短6位'.
                                  'max_length': '密码最多16位',
                                  'required': '密码不能为空'
                              })
    email =forms.EmailField(label='邮箱', 
                            error_messages={
                                'invalid': '邮箱格式不正确'
                            }, required=False)

3.6 forms assembly hook function

For field, by hook function you can also do an additional check

  • Local hook function

    A single additional check fields, using local hook function

class MyForm(forms.Form):
    # ....
    
    def clean_username(self):
        username = self.clean_data.get('username')
        if '卧槽' in username:
            # 给username字段添加错误信息
            self.add_error('username': '小孩子不可以讲脏话哦')
        return username
  • Global hook function

    A plurality of check fields, using a global hook, e.g.

class MyForm(forms.Form):
    # ....
    
    def clean(self):
        password = self.clean_data.get('password')
        re_password = self.clean_data.get('re_password')
        if not password == re_password:
            self.add_error('re_password', '两次密码不一致')
        return self.clean_data

3.7 pairs of fields regular check

from django import forms
from django.core.validators import RegexValidator

class MyForm(forms.Form):
    # ....
    phone = forms.CharField(
        validators=[RegexValidator(r'^[0-9]+$', '请输入数字'), 
                   Regexvalidator(r'^159[0-9]+$', '号码必须以159开头')]
    )

3.8 input box to change the value of the type property

# 改变input框type属性的方法
widget = widgets.TextInput()        # 普通文本
widget = widgets.PaddwordInput()        # 密码

# 让forms组件渲染出来的input框有form-control类属性
# 如果有多个类,用空格隔开
widget = widgets.TextInput(attrs={'class': 'form-control others'})
widget = widgets.PasswordInput(attrs={'class': 'form-control others'})

Guess you like

Origin www.cnblogs.com/zj420255586/p/11761918.html