基于ajax和Form实现的注册
注册
urls.py
from django.contrib import admin
from django.urls import path, re_path
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', views.login),
path('get_valid_img/',views.get_valid_img),
path('zhuce/', views.zhuce),
path('books/', views.book_view),
]
视图 views.py
from django.contrib.auth.models import User
#
from django.contrib import auth
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
from django.http import JsonResponse
from django import forms
from django.forms import widgets
import re
####Form组件
class UserForm(forms.Form): #必须继承Form
user=forms.CharField(min_length=5,
label="用户名",
error_messages={"required":"用户名不能为空"},
# 想type=text的input标签添加个类
widget=widgets.TextInput(attrs={"placeholder":"请您输入用户名","class":"input"})
)
pwd=forms.CharField(error_messages={"required":"密码不能为空"},
label="密码",
min_length=7,
widget=widgets.PasswordInput(attrs={"placeholder":"请您输入数字与字母组合的密码","class":"input"})
)
r_pwd=forms.CharField(error_messages={"required":"密码不能为空"},
label="确认密码",
min_length=7,
widget=widgets.PasswordInput(attrs={"placeholder": "请您再次输入密码","class":"input"})
)
email=forms.EmailField(required=True,
error_messages={"invalid":"邮箱格式错误",
"required":"邮箱不能为空"},
label="邮箱",
widget=widgets.EmailInput(attrs={"placeholder": "请输入您的邮箱","class":"input"})
)
# 局部钩子
def clean_user(self):
# 从第一层校验正确的{:}中取正确的用户名
val=self.cleaned_data.get("user")
user=User.objects.filter(username=val).first()
if not user:
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 re.search("\w+@163.com$",val):
return val
else:
raise ValidationError("邮箱必须是163邮箱!")
# 全局钩子
def clean(self): #如果第一层没通过,空
pwd=self.cleaned_data.get("pwd")
r_pwd=self.cleaned_data.get("r_pwd")
if pwd and r_pwd: #如果全局钩子没有错误,发安徽null,有值,
if pwd==r_pwd: #结构相同,验证通过,返回正确 {:}
return self.cleaned_data
else:
raise ValidationError("两次密码不一样")
else:
return self.cleaned_data
# 另一个简便方法
# if pwd and r_pwd and r_pwd != pwd:
# self.add_error("r_pwd", ValidationError("两次密码不一致!"))
# else:
# return self.cleaned_data
# 注册
def zhuce(request):
if request.method=="POST":
form=UserForm(request.POST)
print(form)
res={"user":None,"err_msg":""}
if form.is_valid():
res["user"]=form.cleaned_data.get("user")
print(form.cleaned_data)
user=form.cleaned_data.get("user")
pwd=form.cleaned_data.get("pwd")
email=form.cleaned_data.get("email")
user=User.objects.create_user(username=user,password=pwd,email=email)
else:
print(form.errors)
print(form.cleaned_data)
res["err_msg"]=form.errors
return JsonResponse(res)
else:
form=UserForm()
return render(request,"zhuce.html",locals())
zhuce.html
<!doctype html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>登录页面</title> <link rel="stylesheet" type="text/css" href="../static/css/styles.css"> <!--[if IE]> <script src="/static/js/html5shiv.min.js"></script> <![endif]--> </head> <body> <div class="jq22-container" style="padding-top:100px"> <div class="login-wrap"> <div class="login-html"> <input id="tab-2" type="radio" name="tab" class="sign-up"><label for="tab-2" class="tab">注册</label> <div class="login-form"> <form action="" method="post"> <div class="sign-up-htm"> {##} {# <div class="group">#} {#label for="username" class="label">用户名</label>#} {#<input id="user" type="text" class="input" placeholder="请在这里输入用户名" name="user">#} {# <span>{}</span>#} {# </div>#} {#div class="group">#} {#label for="password" class="label">密码</label>#} {# input id="pass" type="password" class="input" data-type="password" name="pwd" placeholder="请在这里输入密码">#} {# </div>#} {# div class="group">#} {#label for="password" class="label">确认输入密码</label>#} {# <input id="pass" type="password" class="input" name="pwd" placeholder="请输入密码">#} {# </div>#} {#<div class="group">#} {# <label for="email" class="label">请输入邮箱</label>#} {#<input id="pass" type="text" class="input" placeholder="请在这里输入邮箱" name="email">#} {#</div>#} {% csrf_token %} {% for field in form %} <div class="group"> <label for="">{{ field.label }}</label> {{ field }} <span class="error"></span> </div> {% endfor %} <div class="group"> <input type="button" class="button zhuce_btn" value="注册" style="cursor: pointer"> </div> <div class="hr"></div> <div class="foot-lnk"> <label for="tab-1">会员专属通道</label> </div> </div> </form> </div> </div> </div> </div> <script src="/static/js/jquery.js"></script> <script> $(".zhuce_btn").click(function () { $.ajax({ url: "", type: "post", data: { user: $("#id_user").val(), pwd: $("#id_pwd").val(), r_pwd: $("#id_r_pwd").val(), email: $("#id_email").val(), csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val() }, success: function (res) { {#注册成功#} if (res.user) { location.href = "/login/" } else { {# 先清除注册错误时的错误内容,#} $(".error").html(""); // 移除属性,就是框边色 $(".group").removeClass("has-error"); //展示新错误 $.each(res.err_msg, function (i, j) { {#循环,字符串拼接,渲染出来的input标签的id是id_user,错误信息添加到下面的span标签渲染#} $("#id_" + i).next().html(j[0]).css("color", "red").parent().addClass("has-error") // 同时在父类添加,表格样式has-error }) } } }) }) </script> </body> </html>
效果 :