基于modelform和ajax的注册
forms文件
创建ModelForm组件
from django import forms from crm import models from django.core.exceptions import ValidationError import hashlib #注册form class RegForm(forms.ModelForm): #添加确认密码 按照form组件的样式写 password = forms.CharField(widget=forms.PasswordInput(),required="不能为空",label="密码22",min_length="6") re_password = forms.CharField(widget=forms.PasswordInput(),label="确认密码",min_length="6") class Meta: #指定关联的model model=models.UserProfile #要展示的内容 # fields="__all__" #展示所有的字段 # exclude=["is_active"] #排除这个字段 #或者指定要显示的字段 决定了在页面上的显示顺序 *** 即使是自定义的re_password也可以写进来 fields=["username","name","password","re_password","department","mobile"] #这个label的注释直接在modelform中改 或者 在model中写verbose_name="用户名" #这设置的label只对models里的字段起作用, 自己定义的re_password 不起作用 labels={ #全局设置, 没有加label的字段就还是按数据库里的字段名 "username":"用户名", "password":"密码", "name":"姓名", "department":"部门", } widgets = { # "password":forms.PasswordInput(attrs={"class":"form-control"}) #密码显示密文 } # 单加的报错 只对title做设置 error_messages = { "username":{"required":"不能为空","invalid":"格式错误"}, "department":{"required":"不能为空"}, "mobile":{"required":"不能为空"}, } ##初始化把样式调出来 def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) #调节样式 print(self.fields) #拿到的是对象 for field in self.fields.values(): #field 是取出来的对象 field.error_messages={"required":"不能为空"}#批量处理 field.widget.attrs.update({"class":"form-control"}) def clean(self): #两次密码校验 pwd = self.cleaned_data.get("password") re_pwd = self.cleaned_data.get("re_password") print(self.cleaned_data) if pwd == re_pwd and pwd: #如果密码和确认密码一致, 并且存在 # 两次密码一致 之后对密码进行加密 md5 = hashlib.md5() # MD5对象 md5.update(pwd.encode("utf-8")) #加密结果 pwd = md5.hexdigest() print(pwd) #3c4423d6a2f6dfcac2ad6f6d1981ad35 self.cleaned_data["password"] = pwd print("-->",self.cleaned_data) #{'username': 'sanjiang@qq.com', 'name': 'sanjiang', 'password': '3c4423d6a2f6dfcac2ad6f6d1981ad35', 're_password': 'sanjiang', 'department': <Department: 销售部>, 'mobile': None} return self.cleaned_data else: self.add_error("re_password","两次密码不一致") #把错误提示加到re_password 容易取值 raise ValidationError("两次密码不一致") #错误提示加到了所有的错误里了不容易取值
在views文件中利用modelform实例化
from django.shortcuts import render,HttpResponse,redirect from crm.models import UserProfile from crm.forms import RegForm from django.http import JsonResponse #注册 用ModelForm 和ajax def reg(request): form_obj = RegForm() if request.method=="POST": form_obj = RegForm(request.POST) #用RegForm做校验 res = {"user":None,"err_msg":""} if form_obj.is_valid(): #通过校验 print('通过校验') print(form_obj.cleaned_data) #{'username': 'sanjiang@qq.com', 'name': 'sanjiang', 'password': '3c4423d6a2f6dfcac2ad6f6d1981ad35', 're_password': 'sanjiang', 'department': <Department: 销售部>, 'mobile': None} res["user"] = form_obj.cleaned_data.get("username") # 写入数据到数据库 form_obj.cleaned_data.pop("re_password") #把re_password删除 因为没有在models的字段里 # print(form_obj.cleaned_data) obj = UserProfile.objects.create(**form_obj.cleaned_data) # print(obj) else: # print("错误信息:",form_obj.errors) # print("部分干净信息:",form_obj.cleaned_data) res["err_msg"] = form_obj.errors return JsonResponse(res) return render(request,"reg.html",{"form_obj":form_obj})
注册的html
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册页面</title> <link rel="stylesheet" href="{% static 'plugins/bootstrap/css/bootstrap.css' %}"> </head> <body> <div class="container"> <div class="row" style="margin-top: 70px"> <div class="col-sm-6 col-sm-offset-3"> <form class="form-horizontal" method="post" action="" novalidate> {# {{ form_obj.as_p }}#} {% csrf_token %} {# <div class="form-group">#} {# <label for="{{ form_obj.username.id_for_label }}"#} {# class="col-sm-2 control-label">{{ form_obj.username.label }}</label>#} {# {{ form_obj.username.id_for_label }} 作用就是点击对应的label"用户名" 光标会自动聚焦在这个数入框 #} {# {{ form_obj.username.label }} 作用 显示对应的中文名称 #} {# <div class="col-sm-10">#} {# {{ form_obj.username }}#} {# {{ form_obj.username }} 生成一个username的input输入框 #} {# {{ form_obj.username.errors.0 }}#} {# 错误提示#} {# </div>#} {# </div>#} {##} {# <div class="form-group">#} {# <label for="{{ form_obj.password.id_for_label }}"#} {# class="col-sm-2 control-label">{{ form_obj.password.label }}</label>#} {# <div class="col-sm-10">#} {# {{ form_obj.password }}#} {# {{ form_obj.password.errors.0 }}#} {# </div>#} {# </div>#} {##} {# <div class="form-group">#} {# <label for="{{ form_obj.name.id_for_label }}"#} {# class="col-sm-2 control-label">{{ form_obj.name.label }}</label>#} {# <div class="col-sm-10">#} {# {{ form_obj.name }}#} {# {{ form_obj.name.errors.0 }}#} {# </div>#} {# </div>#} {##} {# <div class="form-group">#} {# <label for="{{ form_obj.department.id_for_label }}"#} {# class="col-sm-2 control-label">{{ form_obj.department.label }}</label>#} {# <div class="col-sm-10">#} {# {{ form_obj.department }}#} {# {{ form_obj.department.errors.0 }}#} {# </div>#} {# </div>#} {# igcrm 中写的 循环取值展示#} {% for field in form_obj %} <div class="form-group"> <label for="">{{ field.label }}</label> {{ field }} <span class="error pull-right">{{ field.errors.0 }}</span> {# 显示错误信息#} </div> {% endfor %} {# 额外添加的确认密码 #} {# <div class="form-group">#} {# <label for="{{ form_obj.re_password.id_for_label }}"#} {# class="col-sm-2 control-label">{{ form_obj.re_password.label }}</label>#} {# <div class="col-sm-10">#} {# {{ form_obj.re_password }}#} {# {{ form_obj.re_password.errors.0 }}#} {# </div>#} {# </div>#} {# <div class="form-group">#} {# <div class="col-sm-offset-2 col-sm-10">#} {# <button type="submit" class="btn btn-default">Sign in</button>#} {# </div>#} {# </div>#} {# <input type="submit" class="btn btn-primary pull-left" id="reg_btn" value="注册">#} 发送ajax请求的时候就不能再使用submit类型了 <input type="button" class="btn btn-primary pull-left" id="reg_btn" value="注册"> </form> </div> </div> </div> <script src="/static/js/jquery.js"></script> <script> $("#reg_btn").click(function(){ {#alert("绑定成功");#} $.ajax({ url:"", type:"post", data:{ username:$("#id_username").val(), name:$("#id_name").val(), password:$("#id_password").val(), re_password:$("#id_re_password").val(), department:$("#id_department").val(), mobile:$("#id_mobile").val(), csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val() }, success:function(res){ console.log('1234'); {#console.log(res);#} if(res.user){ //注册成功 alert("注册成功"); location.href="/login/" }else{ //清除错误 console.log('aaaa') $(".error").html(""); $(".form-group").removeClass("has-error"); //展示新错误 $.each(res.err_msg,function(i,j){ console.log(i,j); $("#id_"+i).next().html(j[0]).css("color","red").parent().addClass("has-error") }) } }, }) }) </script> </body> </html>