标签:type eth log hang pwd 成功 errors col pre
对于前端的表单进行验证的方法,从最简单的js到基于XML传输的Ajax,再到cookie的免认证,现在Django为我们提供了自带的表单验证方法。
views.py:
from django import forms class FM(forms.Form): #这里要接受后端需要的,不需要的数据不会关注 required=‘不能为空‘ username=forms.CharField(error_messages={‘required‘:required}) #表单中的name要与变量名一样 pwd=forms.CharField( max_length=20, min_length=6, error_messages={‘required‘:required, ‘min_length‘:‘密码长度不小于6‘, ‘max_length‘:‘密码长度不大于20‘, } ) email=forms.EmailField( error_messages={ ‘required‘:required, ‘invalid‘:‘邮箱格式错误‘ } ) def fn(request): if request.method==‘GET‘: obj=FM() return render(request,‘fn.html‘,{‘obj‘:obj}) elif request.method==‘POST‘: obj = FM(request.POST) r1=obj.is_valid() #判断是否成功 if r1: print(obj.changed_data) #返回正确信息 else: # print(obj.errors[‘username‘]) #否则返回错误信息 return render(request,‘fn.html‘,{‘obj‘:obj}) return render(request,‘fn.html‘)
html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="fn.html" method="POST"> {% csrf_token %} <p>{{ obj.username}}{{ obj.errors.username.0 }}</p> <p>{{ obj.pwd }}{{ obj.errors.pwd.0 }}</p> <p>{{ obj.email }}{{ obj.errors.email.0 }}</p> <input type="submit" value="提交"> </form> </body> </html>
(别忘了url)
标签:type eth log hang pwd 成功 errors col pre
原文地址:http://www.cnblogs.com/SunsetSunrise/p/7724468.html