django表单验证怎么用

845次阅读
没有评论

django表单验证怎么用

1, 在视图views.py中引入forms模块 from django import forms,特别注意是forms,加s

2, 然后创建一个类继承django的Form class biaodan(forms.Form):

3, 编写自定义的表单验证规则, forms模块中提供了许多内置的验证字段如, 针对字符串使用CharFiled,针对邮箱使用 EmailFiled,针对url地址使用URlFiled,数字字段,ip类的字段等等, 每一个字段内我们还可以设置验证条件,比如,是否要求字段可以为空,添加验证条件required=True,表示不能为空,max_length=5,最大字符数,min_length最小字符数,error_messages={},自定的错误信息,字典形式,键为验证条件的字段,错误信息自己可以随便写,针对邮箱有一个错误信息字段为invalid,用来专门写邮箱验证错误后的提示信息,其实错误信息可以自己不编写,模块中有默认的验证错误返回信息,不过是英文的,为了更好的用户体验,建议自己定义

比如我们定义一个用户的验证

django框架没有手机号的验证规则可以自定义添加

# 编写自定义验证规则def mobile_check(value):
    res = re.match('^1[356789]\d{9}$', value)    if not res:        # 自定义规则不抛异常表示通过
        raise ValidationError('手机号码格式错误')class bd(forms.Form):
    mobile = forms.CharField(
        required=True,        # 使用自定义验证规则
        validators=[mobile_check],
        error_messages={            'required': '手机号为必填项',
        },
    )
    user = forms.CharField(
        required=True,
        max_length=4,
        min_length=2,
        error_messages={'required': '不能为空',  'max_length': '最长不能超过4个字符', 
        'min_length': '最小长度为2'
        }
    )

4, 验证类编写好以后我们就可以,编写逻辑逻辑处理模块了

def test(request):
    if request.method == 'POST':
        f = bd(request.POST) # 使用bd类验证请求过来大的信息
        if f.is_valid():    # is_valid()返回验证是否通过的布尔值
            # print(f.cleaned_data)  # cleaned_data 返回验证通过后的所有数据,字典形式
            # 可以执行数据库存储操作
            return JsonResponse(f.cleaned_data)
        else:
            return render(request, 'kanyun/test.html', {'info': f.errors})  # errors 获取验证错误信息
    elif request.method == 'GET':
        return render(request, 'kanyun/test.html')

通过验证后的返回的cleaned_data数据,可以进行对数据库的存储操作
如果是登陆则可以查询数据库对比,成功后可以执行跳转操作

前端代码,前端的input的输入框下要有接收错误信息的标签模块用来接收错误提示信息

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>From模块验证表单模块使用方法访问页面</h1>
<form action="{% url 'kanyun:test' %}" method="post">
    {% csrf_token %}
    <div>
        用户名:<input type="text" name="mobile"/>
        <span>{{ info.user }}</span>
    </div>
    <div>
        密码:<input type="text" name="user"/>
        <span>{{ info.pwd }}</span>
    </div>
    <button type="submit">提交</button>
</form>
<h1>自动创建表单</h1>

</body>
</html>
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2019-10-04发表,共计2284字。
新手QQ群:570568346,欢迎进群讨论 Python51学习
评论(没有评论)