页面注册系统--使用forms表单结合ajax
页面注册系统--使用forms表单结合ajax
在Django中通过forms构建一个表单
1.urls.py 配置路由
from django.conf.urls import url
from django.contrib import admin
from blog import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/', views.login),
url(r'^get_valid_img/', views.get_valid_img),
url(r'^index/', views.index),
# 用户注册页面 reg
url(r'^reg/', views.reg),
]
2.在app 包路径 创建一个forms.py 用于定义类:
from django import forms
from django.forms import widgets
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
class RegForm(forms.Form):
username = forms.CharField(min_length=5,
# 定义 class 类型 form-control 为 bootcss 样式
widget=widgets.TextInput(attrs={"class": "form-control"})
)
password = forms.CharField(min_length=5,
widget=widgets.PasswordInput(attrs={"class": "form-control"}))
repeat_password = forms.CharField(min_length=5,
widget=widgets.PasswordInput(attrs={"class": "form-control"})
)
email = forms.EmailField(min_length=5,
widget=widgets.TextInput(attrs={"class": "form-control"})
)
# 清洗全局 钩子用于清洗 两次用户输入的密码是否一致
def clean(self):
if self.cleaned_data.get("password") == self.cleaned_data.get("repeat_password"):
return self.cleaned_data
else:
raise ValidationError("两次密码不一致")
3.视图views.py页面配置
from django.shortcuts import render,HttpResponse,redirect
# Create your views here.
from PIL import Image
from django.contrib import auth
from .models import *
import json
from django.contrib.auth.decorators import login_required
from blog.forms import RegForm
def reg(request):
if request.is_ajax():
regForm = RegForm(request.POST)
regResponse = {"user": None, "error_msg": None}
if regForm.is_valid():
username = regForm.cleaned_data.get("username")
password = regForm.cleaned_data.get("password")
# repeat_password = regForm.cleaned_data.get("repeat_password")
email = regForm.cleaned_data.get("email")
user = UserInfo.objects.create_user(username=username, password=password, email=email)
regResponse["user"] = username
else:
regResponse["error_msg"] = regForm.errors
return HttpResponse(json.dumps(regResponse))
# 将forms.py 数据实例化给前端 模板
regForm = RegForm()
return render(request, "reg.html", {"regForm": regForm})
4.模板页面reg.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="/static/css/login.css">
<link rel="stylesheet" href="/static/dist/css/bootstrap.css">
<script src="/static/dist/js/jquery-3.2.1.js"></script>
<script src="/static/dist/js/bootstrap.js"></script>
<script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<form class="col-md-6 col-md-offset-3">
<div class="form-group">
<label for="user">用户名</label>
{{ regForm.username }} <span class="err_msg"></span>
</div>
<div class="form-group">
<label for="pwd">密码</label>
{{ regForm.password }} <span class="err_msg"></span>
</div>
<div class="form-group">
<label for="pwd">确认密码</label>
{{ regForm.repeat_password }} <span class="err_msg"></span>
</div>
<div class="form-group">
<label for="pwd">邮箱</label>
{{ regForm.email }} <span class="err_msg"></span>
</div>
<div class="row">
<div class="col-md-6">
<input type="button" value="登录" class="btn-primary btn Regbtn">
</div>
</div>
</form>
</div>
</div>
<script>
$(".Regbtn").click(function () {
$.ajax({
url:"/reg/",
// csrftoken 值 放在 headers 中
headers:{"X-CSRFToken":$.cookie('csrftoken')},
type:"post",
// 输出序列化表单值的结果: 通过 form定义的 id=reg 属性 .serialize() 可以获取里面所有的键值对
data:$("#reg").serialize(), // 通过serialize() 获取所有的键值对
// http://www.w3school.com.cn/jquery/ajax_serialize.asp // 参考
// data:{ // 与此结果一致
// username:$("#id_username").val(),
// password:$("#id_password").val(),
// repeat_password:$("#id_repeat_password").val(),
// email:$("#id_email").val()
// },
success:function (data) {
var data=JSON.parse(data);
if(data.user){
location.href="/login/"
}
else {
// 在每次 点击提交时,将错误信息清空
$(".err_msg").html("");
var error_dict = data.error_msg;
// 通过 each 循环错误信息,里的 key 和 值
$.each(error_dict,function (i,j) {
console.log(i,j);
// 拼接 forms 生成的 id 标签,在其后面标签添加 内容
$("#id_"+i).next().addClass("pull-right").html(j[0]).css("color","red");
// 判断如果 i 等于 __all__ 全局 清洗 钩子 返回的错误,将错误值放到 id_repeat_password 后面
if(i=="__all__"){
$("#id_repeat_password").next().addClass("pull-right").html(j[0]).css("color","red");
}
})
}
}
})
})
</script>
</body>
</html>