标签:mail required form IV UI ima eth obj 模板
--------------login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login/" method="post"> <p><input type="text" value="用户名" name="username"><span>{{ oo.errors.username.0 }}</span> </p> <p><input type="text" value="邮箱" name="email"><span>{{ oo.errors.email.0 }}</span> </p> <input type="submit" value="提交"> </form> </body> </html>
--------------urls.py
urlpatterns = [ path(‘admin/‘, admin.site.urls), path(‘login/‘,views.login), ]
----------------views.py(创建模板类FormData继承于forms.Form)
from django import forms # Create your views here. class FormData(forms.Form): username=forms.CharField(max_length=6,error_messages={"required":"用户名不能为空","max_length":"长度不能大于6"}) email=forms.EmailField(error_messages={"invalid":"邮箱格式错误"}) def login(req): if req.method=="GET":return render(req,"login.html") elif req.method=="POST": # obj=FormData(req.POST) # status=obj.is_valid() #验证是否成功,如果有其中某一个出错,返回false # print(status) # print(obj.clean()) #拿到验证成功后的值(只拿正确的值,错误的不拿,如果都错了拿到的值为空) # print(obj.errors.as_json) #拿到错误信息 #平常使用 obj=FormData(req.POST) if obj.is_valid(): #如果验证成功 print(obj.clean()) #输出拿到的正确信息 else: print(obj.errors.as_json)#如果验证错误输出错误信息 u=obj.errors[‘username‘][0] e=obj.errors["email"][0] return render(req,"login.html",{"oo":obj})
因为点击提交按钮,界面会刷新,填入的数据会消失,所以有以下方法
---------------login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login/" method="post"> <p> {{ oo.username }} //此处oo不能变,username是模板FormData中的字段 <span>{{ oo.errors.username.0 }}</span> </p> <p> {{ oo.email }} <span>{{ oo.errors.email.0 }}</span> </p> <input type="submit" value="提交"> </form> </body> </html>
---------------views.py
from django import forms # Create your views here. class FormData(forms.Form): username=forms.CharField(max_length=6,error_messages={"required":"用户名不能为空","max_length":"长度不能大于6"}) email=forms.EmailField(error_messages={"invalid":"邮箱格式错误"}) def login(req): if req.method=="GET": obj=FormData() return render(req,"login.html",{"oo":obj}) elif req.method=="POST": #平常使用 obj=FormData(req.POST) if obj.is_valid(): #如果验证成功 print(obj.clean()) #输出拿到的正确信息 else: print(obj.errors.as_json)#如果验证错误输出错误信息 u=obj.errors[‘username‘][0] e=obj.errors["email"][0] return render(req,"login.html",{"oo":obj})
标签:mail required form IV UI ima eth obj 模板
原文地址:https://www.cnblogs.com/gaoyukun/p/9108054.html