bbs 第二天 註冊功能 需要上傳圖片
阿新 • • 發佈:2018-07-06
tin 當前 dcl pri validator 格式不正確 import chan 技術
2.註冊功能:
Django的forms表單中添加字段
from django import forms from django.core.exceptions import ValidationError # Django內置的正則 from django.core.validators import RegexValidator from blog import models class LoginForm(forms.Form): username = forms.CharField( label="用戶名", min_length=3, max_lengthView Code=12, error_messages={ "required": "用戶名不能為空", "min_length": "用戶名最少3位", "max_length": "用戶名最長12位" }, widget=forms.widgets.TextInput( attrs={"class": "form-control c1"} ) ) password = forms.CharField( label="密碼", min_length=4, max_length=12, error_messages={ "required": "密碼不能為空", "min_length": "密碼最短4位", "max_length": "密碼最長12位" }, widget=forms.widgets.PasswordInput( attrs={"class": "form-control"} ) ) # 註冊功能的字段的校驗class RegForm(forms.Form): username = forms.CharField( label="用戶名", min_length=3, max_length=12, error_messages={ "required": "用戶名不能為空", "min_length": "用戶名最短3位", "max_length": "用戶名最長12位" }, widget=forms.widgets.TextInput( attrs={"class": "form-control"} ) ) password = forms.CharField( label="密碼", min_length=3, max_length=12, error_messages={ "required": "密碼不能為空", "min_length": "密碼最短3位", "max_length": "密碼最長12位" }, widget=forms.widgets.PasswordInput( attrs={"class": "form-control"} ) ) re_password = forms.CharField( label="確認密碼", min_length=3, max_length=12, error_messages={ "required": "密碼不能為空", "min_length": "密碼最短3位", "max_length": "密碼最長12位" }, widget=forms.widgets.PasswordInput( attrs={"class": "form-control"} ) ) phone = forms.CharField( label="手機號", min_length=11, max_length=11, validators=[ RegexValidator(r‘^\d{11}$‘, "手機號必須是數字"), RegexValidator(r‘^1[356789][0-9]{9}$‘, "手機號碼格式不正確") ], error_messages={ "required": "手機不能為空!", "min_length": "手機號碼11位", "max_length": "手機號碼11位" }, widget=forms.widgets.TextInput( attrs={"class": "form-control"} ) ) # 鉤子函數 clean_data 取到字段裏面的所有內容 # 局部鉤子 用於校驗一些正常的結果 clean_字段名 def clean_username(self): # 取裏面username字段名的數據 value = self.cleaned_data.get("username", "") if "金瓶" in value: raise ValidationError("名字非法") elif models.UserInfo.objects.filter(username=value): raise ValidationError("用戶名已存在") else: return value # 全局鉤子 用於校驗密碼是否一致 def clean(self): pwd = self.cleaned_data.get(‘password‘, ‘‘) re_pwd = self.cleaned_data.get(‘re_password‘, ‘‘) # 如果密碼不為空或者一致 if re_pwd and pwd == re_pwd: return self.cleaned_data else: err_msg = "兩次密碼不一致或者為空" self.add_error("re_password", err_msg) # raise ValidationError(err_msg)
reg.html頁面
<div class="container"> <div class="row"> <div class="panel panel-primary col-md-8 col-md-offset-2 " id="login-form"> <div class="panel-heading"> <h3 class="panel-title text-center ">註冊界面</h3> </div> <div class="col-md-4 col-md-offset-4" id="login-form"> <form autocomplete="off" novalidate> <div class="form-group"> <label for="{{ form_obj.username.id_for_label }}">{{ form_obj.username.label }}</label> {{ form_obj.username }} <span class="help-block"></span> </div> <div class="form-group"> <label for="{{ form_obj.password.id_for_label }}">{{ form_obj.password.label }}</label> {{ form_obj.password }} <span class="help-block"></span> </div> <div class="form-group"> <label for="{{ form_obj.re_password.id_for_label }}">{{ form_obj.re_password.label }}</label> {{ form_obj.re_password }} <span class="help-block"></span> </div> <div class="form-group"> <label for="{{ form_obj.phone.id_for_label }}">{{ form_obj.phone.label }}</label> {{ form_obj.phone }} <span class="help-block"></span> </div> <div class="form-group"> <label>頭像</label> <div class="col-ms-10"> <input accept="image/*" type="file" id="id_avatar" name="avatar" style="display: none"> <label for="id_avatar"><img src="/static/img/default.png" id="show-avatar"></label> </div> </div> <div class="form-group"> <button id="reg-button" type="button" class="btn btn-default">註冊</button> </div> </form> </div> </div> </div> </div>View Code
views.py
def reg(request): if request.method == ‘POST‘: ret = {‘code‘: 0} # 如果是POST請求就拿到所有form表單裏面的所有數據 form_obj = forms.RegForm(request.POST) # 校驗form裏面的正則數據是否通過 if form_obj.is_valid(): # 把頭像對象拿出來 # 取到前端寫好的FormData對象裏面的所有數據 # 取到圖片對象 頭像 avatar_obj = request.FILES.get(‘avatar‘) # 創建用戶前需要把重復一次的密碼提出來 form_obj.cleaned_data.get(‘re_password‘, ‘‘) # 創建用戶 models.UserInfo.objects.create_user( # 頭像 avatar=avatar_obj, # 所有用戶信息 **form_obj.cleaned_data ) ret[‘data‘] = "/login/" else: # 沒有通過數據校驗 ret[‘code‘] = 1 # 通過data 發送form_obj裏面正則校驗報錯的信息到前端 ret[‘data‘] = form_obj.errors return JsonResponse(ret) # 如果不是POST請求就發送一個空的form表單對象過去前端 form_obj = forms.RegForm() return render(request, "reg.html", {‘form_obj‘: form_obj})View Code
Ajax發送數據:用戶名、密碼、手機、頭像,然後還有頭像預覽
<script> // 找到註冊按鈕綁定點擊事件 $("#reg-button").click(function () { var dataObj = new FormData(); dataObj.append("username", $("#id_username").val()); dataObj.append("password", $("#id_password").val()); dataObj.append("re_password", $("#id_re_password").val()); dataObj.append("phone", $("#id_phone").val()); dataObj.append("avatar", $("#id_avatar")[0].files[0]); $.ajax({ url: "/reg/", type: "POST", processData: false, contentType: false, data: dataObj, success: function (data) { console.log(data); if (data.code) { // 如果有報錯信息,應該在頁面的對應位置展示出來 var errMsgObj = data.data; $.each(errMsgObj, function (k, v) { // k: 字段名 v:報錯信息的數組 // 根據字段名找對應的input標簽,把錯誤信息添加到對應位置 $("#id_" + k).next(".help-block").text(v[0]).parent().parent().addClass("has-error"); }) } else { console.log(data.data); location.href = data.data || "/login/" } } }) }); // 給每一個input標簽綁定focus事件,移除當前的錯誤提示信息 $("input.form-control").focus(function () { $(this).next(".help-block").text("").parent().parent().removeClass("has-error"); }); // 頭像預覽 $("#id_avatar").change(function () { // 找到你選中的那個頭像文件 var fileObj = this.files[0]; console.log(fileObj); // 讀取文件路徑 var fileReader = new FileReader(); fileReader.readAsDataURL(fileObj); // 等圖片被讀取完畢之後,再做後續操作 fileReader.onload = function () { // 設置預覽圖片 $("#show-avatar").attr("src", fileReader.result); }; }) </script>View Code
bbs 第二天 註冊功能 需要上傳圖片