註冊 - urls -前端頁面中寫 username ,password,password,email,頭像 -form組件建立註冊頁面 -widget的做用是,若是不加widget生成的前端標籤是原生的input框,加上以後會變成渲染以後的 -eg:username,password,repeat_pwd,email class RegForm(forms.Form): email = forms.EmailField(widget=widgets.EmailInput( attrs={"class": "form-control", "placeholder": "email"} )) ....還有username,password,repeat_pwd 若是form中有這些字段,則能夠在前端頁面中{{form_obj.username}},{{form_obj.password}}這樣的方式取到值 -驗證每一個字段 - clean_username(self):(用到了局部鉤子) cleaned_data它表明的是一個字典 -ret=models.UserInfo.objects.filter(username=self.cleaned_data.get("username")) if not ret: #校驗字段 return self.cleaned_data.get("username") else: raise ValidationError("用戶名已註冊") -檢查數據庫中是否有username -若是沒有,驗證的那個字段,若是有這個username,則返回cleaned_data取到的值,若是已經存在該用戶,就走ValidationError,顯示error信息 - clean_password(self):(用到了局部鉤子) -同上方法驗證,但須要注意,這個判斷密碼不能全是數字 def clean_validCode(self):(用到全局鉤子) -前端註冊頁面 -上一步在後端上傳的form對象渲染了username,password,email -生成頭像 -<img src="/static/img/default.png" alt="" id="avatar_img"> -<input type="file" class="form-control" id="avatar_file"> (生成一個默認的灰色框頭像,如用戶點擊上傳頭像,此時應該吧圖片遮到上傳的文件上面, 這裏還有讓parent設置成相對定位,children設置絕對定位,還有一點,應該不讓灰色框隱藏, 而是讓他的透明度爲0) -頭像預覽 -找到頭像標籤,用到change事件,用一個變量去接受當前拿到的文件,而後對去到該文件的路徑,讓他付給this.result $("#avatar_file").change(function () { var ele_file=$(this)[0].files[0]; //拿到當前點擊的文件 var reader=new FileReader(); //建立一個新對象 reader.readAsDataURL(ele_file); reader.onload=function (){ $("#avatar_img")[0].src=this.result } }); - Ajax提交數據 -使用formdata是由於裏面有二進制文件 - 上傳二進制文件引入 FormData() - FormData()對象追加鍵值對 -$("#avatar_file")[0].files[0]) # jquery轉DOM對象,取files對象最近一次上傳的文件 $.ajax({ url:"/reg/", type:"POST", data:formdata, contentType:false, processData:false, headers:{"X-CSRFToken":$.cookie('csrftoken')}, //爲了不Forbedent禁止 success:function (data) { console.log(data); var data=JSON.parse(data); //能拿到user表明註冊成功,跳轉到登陸頁面 if (data.user){ location.href="/login/" } //反之 else{ console.log(data.errorsList); $.each(data.errorsList,function (i,j) { console.log(i,j); $span=$("<span>"); $span.addClass("pull-right").css("color","red"); $span.html(j[0]); $("#id_"+i).after($span).parent().addClass("has-error"); if (i=="__all__"){ $("#id_repeat_pwd").after($span) } }) } 註釋:i爲出錯form組件字段、j爲報錯 each循環報錯信息、新建span標籤,給其增長樣式(右漂浮,紅色) span的內容爲報錯信息 給出錯的input標籤後邊添加span標籤,並使其父級標籤has-error 若是i使__all__:將報錯添加到從新輸入密碼後邊的span中 -後端註冊(views中) -判斷是不是is_ajax請求 -接收從前端提交過來的數據 -form驗證 實例化對象,而後進行校驗,將校驗的結果和數據庫進行匹配驗證,獲取校驗結果,cleaned_data是一個字典的形式, 若是校驗失敗,則走errors錯誤信息的列表 form_obj=forms.RegForm(request.POST) #接收從前端提交來的數據,規則和數據放在一塊兒 if form_obj.is_valid():(開始校驗,並獲取校驗結果) username = form_obj.cleaned_data["username"] password = form_obj.cleaned_data["password"] email = form_obj.cleaned_data.get("email") avatar_img = request.FILES.get("avatar_img") ................ -setting.py 若是隻在這裏設置 不在前端設置 用戶接收不到文件 MEDIA_ROOT=os.path.join(BASE_DIR,"app01","media") MEDIA_URL="/media/" -urls.py # media 配置 from django.views.static import serve from blog import settings url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> <script src="/static/dist/js/jquery-3.1.1.js"></script> <script src="/static/dist/js/bootstrap.js"></script> <link rel="stylesheet" href="/static/dist/css/bootstrap.css"> <link rel="stylesheet" href="/static/dist/css/reg.css"> <script src="/static/js/jquery.cookie.js"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-5 col-md-offset-3"> <h1>歡迎進入註冊頁面</h1> <form> {% csrf_token %} <div class="form-group"> <label for="username">用戶名</label> {{ form_obj.username }} </div> <div class="form-group"> <label for="password">密碼</label> {{ form_obj.password }} </div> <div class="form-group"> <label for="password">確認密碼</label> {{ form_obj.repeat_pwd }} </div> <div class="form-group"> <label for="email">郵箱</label> {{ form_obj.email }} </div> <div class="form-group avatar"> <label for="avatar">頭像</label> <img src="/static/img/default.png" alt="" id="avatar_img"> <input type="file" class="form-control" id="avatar_file" > </div> <input type="button" value="提交" class="btn btn-primary" id="subBtn"><span class="error"></span> </form> </div> </div> </div> <script> // 頭像預覽 $("#avatar_file").change(function () { //定位到圖片文件 var ele_file=$(this)[0].files[0]; //this.files var reader=new FileReader(); reader.readAsDataURL(ele_file); reader.onload=function () { $("#avatar_img")[0].src=this.result } }); $("#subBtn").click(function () { var formdata=new FormData(); formdata.append("username",$("#id_username").val()); formdata.append("password",$("#id_password").val()); formdata.append("repeat_pwd",$("#id_repeat_pwd").val()); formdata.append("email",$("#id_email").val()); formdata.append("avatar_img",$("#avatar_file")[0].files[0]); $.ajax({ url:"/reg/", type:'POST', data:formdata, contentType:false, processData:false, headers:{"X-CSRFToken":$.cookie('csrftoken')}, success:function (data) { console.log(data); var data=JSON.parse(data); if (data.user){ location.href="/login/" } else { console.log(data.errorsList); $.each(data.errorsList,function (i,j) { console.log(i,j); $span=$("<span>"); $span.addClass("pull-right").css("color","red"); $span.html(j[0]); $("#id_"+i).after($span).parent().addClass("has-error") if (i=="__all__"){ $("#id_repeat_pwd").after($span) } }) } } }) }) </script> </body> </html>
三視圖函數css
def reg(request): if request.is_ajax(): form_obj = forms.RegForm(request, request.POST) regResponse = {"user": None, "errorsList": None} if form_obj.is_valid(): username = form_obj.cleaned_data["username"] password = form_obj.cleaned_data["password"] email = form_obj.cleaned_data.get("email") avatar_img = request.FILES.get("avatar_img") user_obj = models.UserInfo.objects.create_user(username=username, password=password, email=email, avatar=avatar_img, nickname=username) print(user_obj.avatar, "......") regResponse["user"] = user_obj.username else: regResponse["errorsList"] = form_obj.errors import json return HttpResponse(json.dumps(regResponse)) form_obj = forms.RegForm(request) return render(request, "reg.html", {"form_obj": form_obj})