后台验证插件forms(基于ajax传输数据)
1.视图函数
from django.shortcuts import render, HttpResponse,redirect,reverse
from django import forms
from django.forms import widgets
import json
from django.core.exceptions import ValidationError
from loginapp import models
# Create your views here.
class Login_forms(forms.Form):
user = forms.CharField(max_length=10, min_length=3, label='用户名', required=True,
widget=widgets.TextInput(attrs={'id': 'user','class':'col-md-6'}),
error_messages={'max_length':'最大长度为10','min_length':'最短长度为3','required':'不能为空'})
pwd = forms.CharField(max_length=20, min_length=3, label='密码', required=True,
widget=widgets.PasswordInput(attrs={'id': 'pwd','class':'col-md-6'}),
error_messages={'max_length':'最大长度为20','min_length':'最短长度为3','required':'不能为空'})
pwd_rs = forms.CharField(max_length=20, min_length=3, label='确认密码', required=True,
widget=widgets.PasswordInput(attrs={'id': "pwd2",'class':'col-md-6'}),
error_messages={'max_length': '最大长度为20', 'min_length': '最短长度为3', 'required': '不能为空'})
email = forms.EmailField(label='邮箱', required=True,
widget=widgets.EmailInput(attrs={'id': "email",'class':'col-md-6'}),
error_messages={'required':'不能为空!','invalid': '不符合邮箱格式'})
def clean(self):
pwd = self.cleaned_data.get('pwd')
pwd_rs = self.cleaned_data.get('pwd_rs')
if pwd == pwd_rs:
return self.cleaned_data
else:
raise ValidationError('两次密码不一致')
def clean_user(self):
user = self.cleaned_data.get('user')
user_pd = models.User.objects.filter(user=user).first()
if user_pd:
raise ValidationError('用户名已存在!')
else:
return user
def login(request):
if request.method == "GET":
forms = Login_forms()
if request.method == 'POST':
msg_dic = json.loads(request.body.decode('utf-8'))
# print(msg_dic)
forms = Login_forms(msg_dic)
if forms.is_valid():
forms.cleaned_data.pop('pwd_rs')
# print(forms.cleaned_data)
models.User.objects.create(**forms.cleaned_data)
return HttpResponse(json.dumps('s'))
else:
# print(forms.cleaned_data, '不通过')
return HttpResponse(json.dumps(forms.errors))
return render(request, 'login.html', locals())
2.模板层
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>登录</title>
{% load static %}
<script src={% static 'jquery-3.3.1.js' %}></script>
<script src="/static/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
<link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
</head>
<body>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h2>用户注册</h2>
{% for form in forms %}
<p>{{ form.label }}:</p>
<p>{{ form }}<p id={{ form.name }}sp> </p></p>
{% endfor %}
<p id="res" class="col-md-8"> </p>
<button type="button" class="btn btn-success col-md-6" id="btn">注册</button>
</div>
</div>
</body>
<script>
$('#btn').click(function () {
var msg_dic = {
'user': $('#user').val(),
'pwd': $('#pwd').val(),
'pwd_rs': $('#pwd2').val(),
'email': $('#email').val()
};
msg_dic = JSON.stringify(msg_dic);
$.ajax({
url: '/login/',
type: 'post',
contentType: 'application/json',
data: msg_dic,
dataType: 'json',
success: function (data) {
{#console.log(data);#}
if (data == 's') {
{#console.log(typeof data);#}
location.href = '/cg/'
} else {
if (data.user) {
$('#usersp').text(data.user);
} else {
$('#usersp').html(' ');
}
if (data.pwd) {
$('#pwdsp').text(data.pwd);
} else {
$('#pwdsp').html(' ');
}
if (data.pwd_rs) {
$('#pwd_rssp').text(data.pwd_rs);
} else {
$('#pwd_rssp').html(' ');
}
if (data.email) {
$('#emailsp').text(data.email);
} else {
$('#emailsp').html(' ');
}
if (data.__all__) {
$('#res').text(data.__all__);
}else{
$('#res').html(' ');
}
}
}
})
})
</script>
</html>
3.基础知识
字段参数
//字段参数
max_length=最大值
min_length=最小值
label=标签label中字符
required=判断是否可以为空 True不能为空 False可以为空
widget = 输入框的属性 widget=widgets.TextInput(attrs={'id': 'user', 'class': 'col-md-6'})
error_messages= 错误信息 error_messages={'max_length': '最大长度为10', 'min_length': '最短长度为3', 'required': '不能为空'})
局部钩子校验
//定义一个函数,名字叫:clean_字段名字,内部,取出该字段,进行校验,如果通过,将该字段返回,如果失败,抛异常(ValidationError)
def clean_user(self):
user = self.cleaned_data.get('user')
user_pd = models.User.objects.filter(user=user).first()
if user_pd:
raise ValidationError('用户名已存在!')
else:
return user
全局钩子校验
//程序能走到该函数,前面校验已经通过了,所以可以从cleaned_data中取出密码和确认密码
def clean(self):
pwd = self.cleaned_data.get('pwd')
pwd_rs = self.cleaned_data.get('pwd_rs')
if pwd == pwd_rs:
return self.cleaned_data
else:
raise ValidationError('两次密码不一致')