通用的Django注冊(cè)功能模塊實(shí)現(xiàn)方法
應(yīng)用forms組件實(shí)現(xiàn)用戶輸入信息的校驗(yàn)。首先在app目錄下創(chuàng)建一個(gè)myform.py的文件。
如果你的項(xiàng)目至始至終只用到一個(gè)forms組件那么你可以直接建一個(gè)py文件書寫即可。
但是如果你的項(xiàng)目需要使用多個(gè)forms組件,那么你可以創(chuàng)建一個(gè)myforms文件夾在文件夾內(nèi),根據(jù)forms組件功能的不同創(chuàng)建不同的py文件。
regform.py loginform.py userform.py orderform.py......
# 書寫針對(duì)用戶表的forms主鍵代碼from django import formsfrom app01 import modelsclass MyRegForm(forms.Form): username = forms.CharField(label=’用戶名’,min_length=3,max_length=8,error_messages={ ’required’:’用戶名不能為空’, ’min_length’:’用戶名最少3位’, ’max_length’:’用戶名最大8位’},# 還需要讓標(biāo)簽有Bootstrap樣式widget=forms.widgets.TextInput(attrs={’class’:’form-control’})) password = forms.CharField(label=’密碼’,min_length=3,max_length=8,error_messages={ ’required’:’密碼不能為空’, ’min_length’:’密碼最少3位’, ’max_length’:’密碼最大8位’},# 還需要讓標(biāo)簽有Bootstrap樣式widget=forms.widgets.PasswordInput(attrs={’class’:’form-control’})) confirm_password = forms.CharField(label=’確認(rèn)密碼’,min_length=3,max_length=8, error_messages={ ’required’:’確認(rèn)密碼不能為空’, ’min_length’:’確認(rèn)密碼最少3位’, ’max_length’:’確認(rèn)密碼最大8位’ }, # 還需要讓標(biāo)簽有Bootstrap樣式 widget=forms.widgets.PasswordInput(attrs={’class’:’form-control’}) ) email = forms.EmailField(label=’郵箱’, error_messages={ ’required’: ’郵箱不能為空’, ’invalid’:’郵箱格式不正確’, }, widget=forms.widgets.EmailInput(attrs={’class’:’form-control’}) ) # 鉤子函數(shù) # 局部鉤子:校驗(yàn)用戶名是否已存在 def clean_username(self): username = self.cleaned_data.get(’username’) # 去數(shù)據(jù)庫(kù)中校驗(yàn) is_exist = models.UserInfo.objects.filter(username=username) if is_exist: # 提示信息 self.add_error(’username’,’用戶名已存在’) return username # 全局鉤子:校驗(yàn)兩次密碼是否一致 def clean(self): password = self.cleaned_data.get(’password’) confirm_password = self.cleaned_data.get(’confirm_password’) if not password == confirm_password: self.add_error(’confirm_password’,’兩次密碼不一致’) return self.cleaned_data
然后在urls.py中配置注冊(cè)頁(yè)的路由信息。
from django.contrib import adminfrom django.urls import pathfrom app01 import viewsurlpatterns = [ path(’admin/’, admin.site.urls), path(’register/’,views.register,name=’reg’),]
在視圖函數(shù)views.py中編寫forms組件檢驗(yàn)、ajax發(fā)送的post請(qǐng)求獲取數(shù)據(jù)、調(diào)用django orm功能存儲(chǔ)數(shù)據(jù)、將后端的處理結(jié)果返回給前端進(jìn)行校驗(yàn)。
from app01.myforms import MyRegFormfrom app01 import modelsfrom django.http import JsonResponse# Create your views here.def register(request): form_obj = MyRegForm() if request.method == ’POST’: # 定義返回給前端的js數(shù)據(jù)結(jié)果 back_dic = {'code': 1000, ’msg’: ’’} # 校驗(yàn)數(shù)據(jù)是否合法 form_obj = MyRegForm(request.POST) # 判斷數(shù)據(jù)是否合法 if form_obj.is_valid(): # form_obj.cleaned_data:{’username’: ’zhangsan’, ’password’: ’123456’, ’confirm_password’: ’123456’, ’email’: ’123@qq.com’} # 將校驗(yàn)通過(guò)的數(shù)據(jù)字典賦值給一個(gè)變量 clean_data = form_obj.cleaned_data # 將字典里面的confirm_password鍵值對(duì)刪除 clean_data.pop(’confirm_password’) # {’username’: ’zhangsan’, ’password’: ’123456’, ’email’: ’123@qq.com’} # 注意用戶頭像是一個(gè)圖片的文件,request.POST中只有鍵值對(duì)的數(shù)據(jù) file_obj = request.FILES.get(’avatar’) ''' 針對(duì)用戶頭像一定要判斷是否傳值,不能直接添加到字典里面去 否則file_obj=None,會(huì)將數(shù)據(jù)庫(kù)中默認(rèn)的圖片路徑覆蓋。 ''' if file_obj:# 向字典數(shù)據(jù)clean_data中增加一個(gè)圖片頭像的字段clean_data[’avatar’] = file_obj # 操作數(shù)據(jù)庫(kù)保存數(shù)據(jù) models.UserInfo.objects.create_user(**clean_data) # 注冊(cè)成功則跳轉(zhuǎn)到登錄頁(yè)面 back_dic[’url’] = ’/login/’ else: back_dic[’code’] = 2000 # 校驗(yàn)存在錯(cuò)誤 back_dic[’msg’] = form_obj.errors # 將字典類型的數(shù)據(jù)封裝成json返回到前端 return JsonResponse(back_dic) return render(request,’register.html’,locals())
前端的注冊(cè)頁(yè)面:register.html
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <!-- Bootstrap --> <link rel='external nofollow' rel='stylesheet'> <script src='https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js'> <script src='https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js'></script> <title>用戶注冊(cè)</title></head><body><div class='container-fluid'> <div class='row'> <div class='col-md-8 col-md-offset-2'> <h1 class='text-center'>注冊(cè)</h1> <form id='myform'> <!--這里我們不用form表單提交數(shù)據(jù) 知識(shí)單純的用一下form標(biāo)簽而已-->{% csrf_token %}{% for form in form_obj %} <div class='form-group'> <label for='{{ form.auto_id }}'>{{ form.label }}</label> {{ form }} <span class='pull-right'></span> </div>{% endfor %}<div class='form-group'> <label for='myfile'>頭像 {% load static %} <img src='http://www.cgvv.com.cn/bcjs/{% static ’img/default.jpg’ %}' id=’myimg’ alt='' style='margin-left: 10px'> </label> <input type='file' name='avatar' ></div><input type='button' value='注冊(cè)' id='id_commit'> </form> </div> </div></div></body></html>
【重難點(diǎn)】在于書寫JS處理邏輯:包括了圖片上傳加載、ajax發(fā)送的post請(qǐng)求以及后端注冊(cè)結(jié)果的信息處理。
<script> $('#myfile').change(function () { // 文件閱讀器對(duì)象 // 1 先生成一個(gè)文件閱讀器對(duì)象 let myFileReaderObj = new FileReader(); // 2 獲取用戶上傳的頭像文件 let fileObj = $(this)[0].files[0]; // 3 將文件對(duì)象交給閱讀器對(duì)象讀取 myFileReaderObj.readAsDataURL(fileObj) // 異步操作 IO操作 // 4 利用文件閱讀器將文件展示到前端頁(yè)面 修改src屬性 // 等待文件閱讀器加載完畢之后再執(zhí)行 myFileReaderObj.onload = function(){ $(’#myimg’).attr(’src’,myFileReaderObj.result) } }) $(’#id_commit’).click(function () { // 發(fā)送ajax請(qǐng)求 我們發(fā)送的數(shù)據(jù)中即包含普通的鍵值也包含文件 let formDataObj = new FormData(); // 1.添加普通的鍵值對(duì) {#console.log($(’#myform’).serializeArray()) // [{},{},{},{},{}] 只包含普通鍵值對(duì)#} $.each($(’#myform’).serializeArray(),function (index,obj) { {#console.log(index,obj)#} // obj = {} formDataObj.append(obj.name,obj.value) }); // 2.添加文件數(shù)據(jù) formDataObj.append(’avatar’,$(’#myfile’)[0].files[0]); // 3.發(fā)送ajax請(qǐng)求 $.ajax({ url:'', type:’post’, data:formDataObj, // 需要指定兩個(gè)關(guān)鍵性的參數(shù) contentType:false, processData:false, success:function (args) {if (args.code==1000){ // 跳轉(zhuǎn)到登陸頁(yè)面 //window.location.href = args.url}else{ // 如何將對(duì)應(yīng)的錯(cuò)誤提示展示到對(duì)應(yīng)的input框下面 // forms組件渲染的標(biāo)簽的id值都是 id_字段名 $.each(args.msg,function (index,obj) { {#console.log(index,obj) // username ['用戶名不能為空']#} let targetId = ’#id_’ + index; $(targetId).next().text(obj[0]).parent().addClass(’has-error’) })} } }) }) // 給所有的input框綁定獲取焦點(diǎn)事件 $(’input’).focus(function () { // 將input下面的span標(biāo)簽和input外面的div標(biāo)簽修改內(nèi)容及屬性 $(this).next().text(’’).parent().removeClass(’has-error’) })</script>
效果如下:
以上就是通用的Django注冊(cè)功能模塊實(shí)現(xiàn)步驟的詳細(xì)內(nèi)容,更多關(guān)于Django注冊(cè)功能模塊實(shí)現(xiàn)的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Python結(jié)合百度語(yǔ)音識(shí)別實(shí)現(xiàn)實(shí)時(shí)翻譯軟件的實(shí)現(xiàn)2. 教你JS更簡(jiǎn)單的獲取表單中數(shù)據(jù)(formdata)3. 如何通過(guò)vscode運(yùn)行調(diào)試javascript代碼4. Python基于QQ郵箱實(shí)現(xiàn)SSL發(fā)送5. 測(cè)試模式 - XSL教程 - 56. 解決Java中的java.io.IOException: Broken pipe問(wèn)題7. JAVA抽象類及接口使用方法解析8. python如何寫個(gè)俄羅斯方塊9. 《CSS3實(shí)戰(zhàn)》筆記--漸變?cè)O(shè)計(jì)(一)10. python b站視頻下載的五種版本
