views.py
from django import forms from django.forms import fields from django.forms import widgets class UserForm(forms.Form): username = fields.CharField( required=True,error_messages={'required':'用户名不能为空'}, widget=widgets.TextInput(attrs={'class':'form-control'}) ) #正则表达式 password = fields.CharField(required=True,error_messages={'required':'用户名不能为空'}, widget=widgets.TextInput(attrs={'class':'form-control'}) )#正则表达式 email = fields.EmailField(required=True,error_messages={'required':'用户名不能为空','invalid':'邮箱格式错误'}, widget=widgets.TextInput(attrs={'class': 'form-control'}) ) #正则表达式 def add_user(request): if request.method == 'GET': obj = UserForm() return render(request,'add_user.html',{'obj':obj}) else: # 获取用户提交的数据 request.POST # 获取正则表达式进行验证 # 1. 是否验证成功 # 2. 成功: 获取数据 # 3. 失败: 错误信息 obj = UserForm(request.POST) # 1. 是否验证成功 if obj.is_valid(): print("验证通过",obj.cleaned_data) #添加到数据库 models.UserInfo.objects.create(**obj.cleaned_data) else: pass # print("错误信息",obj.errors) # print("错误信息",obj.errors["username"][0]) # print("错误信息",obj.errors["password"][0]) # print("错误信息",obj.errors["email"][0]) return render(request, 'add_user.html',{'obj':obj})
add_user.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.css"> </head> <body> <div style=" 600px;margin: 0 auto;"> <form method="POST" action="/add-user"> {% csrf_token %} <div class="form-group"> <label for="inputEmail3">用户名</label> <!--<input type="text" name="username" class="form-control" placeholder="用户名" value="{{ obj.cleaned_data.username }}"> --> {{ obj.username }} <span>{{ obj.errors.username.0 }}</span> </div> <div class="form-group"> <label>密码</label> <!-- <input type="text" name="password" class="form-control" placeholder="密码" value="{{ obj.cleaned_data.password }}"> --> {{ obj.password }} <span>{{ obj.errors.password.0 }}</span> </div> <div class="form-group"> <label>邮箱</label> <!-- <input type="text" name="email" class="form-control" placeholder="邮箱" value="{{ obj.cleaned_data.email }}"> --> {{ obj.email }} <span>{{ obj.errors.email.0 }}</span> </div> <button type="submit" class="btn btn-default">添加</button> </form> </div> </body> </html>