Django之form模板的使用

form模块的简介与用处

1.form 是前后端交互的一种方式, form表单提交的一种,django中有一个模块是form他主要用处就过滤前端form提交的数据

1. forms 模块是处理前后台的页面渲染作用:
2. forms 可以吧后端的异常处理反馈给前端消息,还可以设置用户输入的匹配法则, 有局部钩子做过滤,还有全局钩子做过滤

2.forms 模块检测前端提交的数据是否合法, 可以自定义局部钩子和全局钩子进行判断

后端:
from django import forms
class CheckForm2(forms.Form):
    # 校验需求:账号必须不能以数字开头
    usr = forms.CharField(min_length=3, max_length=10, label="账号:",
                          error_messages={
                              'required': "必填项",
                              'min_length': "最少3",
                              'max_length': "最多10"
                          })
    pwd = forms.CharField(min_length=3, max_length=10, label="密码:",
                          error_messages={
                              'required': "必填项",
                              'min_length': "最少3",
                              'max_length': "最多10"
                          },
                          widget=forms.PasswordInput(attrs={
                              'class': 'pwd',                       #定义class
                              'placeholder': '请输入密码'            #设置默认提示
                          })
                          )
    re_pwd = forms.CharField(min_length=3, max_length=10, label="确认:",
                             error_messages={
                                 'required': "必填项",
                                 'min_length': "最少3",
                                 'max_length': "最多10"
                             },
                             widget=forms.PasswordInput)            #设置成密文输入
    email = forms.EmailField(label="邮箱:",
                             error_messages={
                                 'invalid': "格式不正确",
                                 'required': "必填项"
                             }
                             )

    # 局部钩子:对usr进行局部钩子的校验,该方法会在usr属性校验通过后,系统调用该方法继续校验
    def clean_usr(self):
        cleaned_usr = self.cleaned_data.get('usr', None)  # type: str
        # 通过正则匹配不能以数字开头
        import re
        if re.match('^[0-9]', cleaned_usr):
            from django.core.exceptions import ValidationError
            raise ValidationError('不能以数字开头')
        return cleaned_usr

    # 全局钩子:代表校验类中的所有属性校验通过后,系统调用该方法继续校验
    def clean(self):
        cleaned_pwd = self.cleaned_data.get('pwd', None)
        cleaned_re_pwd = self.cleaned_data.get('re_pwd', None)
        if cleaned_pwd != cleaned_re_pwd:
            from django.core.exceptions import ValidationError
            raise ValidationError('两次密码不一致')
        return self.cleaned_data


def register2(request):
    if request.method == "GET":
        check_form2 = CheckForm2()                              #这里一定要生成空对象,不然前端东西无法看到,渲染到
    if request.method == "POST":
        check_form2 = CheckForm2(request.POST)
        if check_form2.is_valid():
            return HttpResponse('注册成功')
        else:
            print(check_form2.errors.as_data)                   #这个是局部的,把后端的报错信息渲染给前端, 这个单个属性
            all_error = check_form2.errors.get('__all__')       #把后端的报错信息渲染给前端页面显示 ,全局都能显示出来
    return render(request, 'register2.html', locals())
后端的视图函数案例
{#渲染方式二#}
<form action="" method="post" novalidate>
    {% for ele in check_form2 %}        //循环列表中的对象//
        <p>
            <label for="">{{ ele.label }}</label>       /对象的label标签属性显示
            {{ ele }}
            <span style="color: red;">{{ ele.errors.0 }}</span>     /去数组中的第一个就对了/ j
            {% if ele == check_form2.re_pwd %}
                <span style="color: red;">{{ all_error.0 }}</span>  /设置特定的报错信息渲染/
            {% endif %}
        </p>
    {% endfor %}
    <input type="submit" value="注册">
</form>
<hr>
{#渲染方式一#}
<form action="" method="post" novalidate>
    <p>
        <label for="id_usr">账号:</label>
        {{ check_form2.usr }}
    </p>
    <p>
        <label for="id_pwd">密码:</label>
        {{ check_form2.pwd }}
    </p>
    <p>
        <label for="id_re_pwd">确认:</label>
        {{ check_form2.re_pwd }}
    </p>
    <p>
        <label for="id_email">邮箱:</label>
        {{ check_form2.email }}
    </p>
    <input type="submit" value="注册">
</form>

</body>
</html>
前端的页面渲染处理

#主要作用就是进行用户注册进行二次过滤, 比如不能数字开头,确认密码与第一次输入密码是否一致等等!!!

猜你喜欢

转载自www.cnblogs.com/gukai/p/10776051.html