Django的Form主要功能
生成HTML标签 验证用户数据(显示错误信息) HTML Form提交保留上次提交数据 初始化页面显示内容
登录通过Form实现
""" django forms 使用练习 """ from django.shortcuts import render from django.shortcuts import redirect from django.shortcuts import HttpResponse import json from datetime import date from datetime import datetime from django import forms class LoginForm(forms.Form): # 模版中的元素 error_messages自定义错误提示信息 user = forms.CharField(min_length=6,error_messages={"required": '用户名不能为空','min_length': '用户名长度不能小6'}) email = forms.EmailField(error_messages={"required": '邮箱不能为空','invalid': '邮箱格式错误'}) def formlogin(request): if request.method == "GET": obj = LoginForm() return render(request,'formlogin.html',{'oo': obj}) elif request.method == "POST": obj = LoginForm(request.POST) """ #print(obj) #<tr><th><label for="id_user">User:</label></th><td><input type="text" name="user" value="123456" minlength="6" required id="id_user"></td></tr> #<tr><th><label for="id_email">Email:</label></th><td><input type="email" name="email" value="11@qq.com" required id="id_email"></td></tr> #print(type(obj)) #<class 'app01.views.LoginForm'> #验证 user和email验证都通过status才等于True否则等于False status = obj.is_valid() #获取正确信息 sucess_obj = obj.clean() #获取错误信息 error_obj = obj.errors #print(sucess_obj,type(sucess_obj)) #{'user': '123456'} sucess_obj是类 <class 'dict'> #print(error_obj,type(error_obj)) #<ul class="errorlist"><li>email<ul class="errorlist"><li>Enter a valid email address.</li></ul></li></ul> error_obj是类 <class 'django.forms.utils.ErrorDict'> """ if obj.is_valid(): #所有字段均验证通过获取用户输入的信息 value_dict = obj.clean() print(value_dict) # create(**value_dict) else: #如果用户输入某个字段验证通过,obj.errors['user']会报KeyError 因为'user'键不存在 #print(obj.errors['user'][0]) #用户名长度不能小6 #print(obj.errors['email'][0]) #邮箱格式错误 pass return render(request, 'formlogin.html',{"oo":obj})views.py
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="formlogin" method="post"> {% csrf_token %} <div> <!--<input id="user" type="text" name="user">--> <!--根据form自动生成html标签--> {{ oo.user }} <!--如有错误显示错误信息--> <span>{{ oo.errors.user.0 }}</span> </div> <div> <!--<input id="pwd" type="text" name="email">--> {{ oo.email }} <span>{{ oo.errors.email.0 }}</span> </div> <div> <label></label> <input type="submit" value="登录"> </div> </form> </body> </html>formlogin.html