html页面代码
<div class="page-header"> <h1>方法2 <small>阿波罗图书管理系统</small> </h1> </div> <form id="b_reg" action="{% url 'b_reg' %}" method="POST"> {% csrf_token %} <label for="usr">usr</label> <input type="text" name="usr" id="usr"> <span>{{ errors.usr.0 }}</span> <br><br> <label for="pwd">pwd</label> <input type="password" name="pwd" id="pwd"> <span>{{ errors.pwd.0 }}</span> <br><br> <label for="age">age</label> <input type="text" name="age" id="age"> <span>{{ errors.age.0 }}</span> <br><br> <label for="email">email</label> <input type="text" name="email" id="email"> <span>{{ errors.email.0 }}</span> <br><br> <input type="submit" value="提交"/> <input type="button" value="Ajax提交" id="Ajax"> <br><br> </form>
form组件代码(这个代码放在views.py文件中即可)
# ################### form组件验证 ###################
class UserInfoForm(forms.Form):
usr = fields.CharField(
max_length=18,
min_length=5,
required=True,
error_messages={
'required': '用户名不能为空',
'max_length': '用户名太长了,大于18位',
'min_length': '用户名太短了,少于8位'
}
)
pwd = fields.CharField(
required=True,
min_length=5,
max_length=32,
error_messages={
'required': '密码不能为空',
'invalid': '密码格式不正确',
'max_length': '密码不能超过32位',
'min_length': '密码不能低于8位',
}
)
age = fields.IntegerField(
required=True,
error_messages={
'required': '年龄不能为空',
'invalid': '年龄必须是数字',
}
)
email = fields.EmailField(
required=True,
min_length=8,
error_messages={
'required': '邮箱不能为空',
'invalid': '邮箱格式不正确',
}
)
def clean_usr(self):
val = self.cleaned_data.get("usr")
ret = UserInfo.objects.filter(usr=val).first()
if not ret:
return val
else:
raise ValidationError("用户名已存在!")
def clean_pwd(self):
val = self.cleaned_data.get("pwd")
if val.isdigit():
raise ValidationError("密码不能是纯数字!")
else:
return val
def clean_email(self):
val = self.cleaned_data.get('email')
if val.endswith('163.com'):
return val
else:
raise ValidationError('请填写163邮箱')
注册的视图函数(此处代码放在views.py中即可)
def b_reg(request):
# 处理GET请求
if request.method == "GET":
return render(request, "b_reg.html")
# 处理POST请求
else:
# 处理POST请求
obj = UserInfoForm(request.POST)
# 是否全部验证成功
if obj.is_valid():
# 用户提交的数据
print(obj.changed_data)
# 将信息写入到数据库
UserInfo.objects.create(**obj.cleaned_data)
# 获取注册用户名
user = request.POST.get("usr")
# 获取注册用户密码
pwd = request.POST.get("pwd")
# 创建用户
User.objects.create_user(username=user, password=pwd)
# 注册成功,重定向到登录页面
return redirect("/book/b_login/")
else:
# 正确信息
clean_data = obj.changed_data
# 错误信息
error_data = obj.errors
return render(request, 'f_reg_gouzi.html', {'errors': error_data, 'clean_data': clean_data})
urls.py文件的配置
from django.urls import path, re_path, include from book import views urlpatterns = [ re_path('^b_reg/', views.b_reg, name='b_reg'), ] #此处使用了路由分发,上一次目录是/book/