国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-a级毛片无码免费真人-a级毛片毛片免费观看久潮喷

您的位置:首頁技術(shù)文章
文章詳情頁

通用的Django注冊功能模塊實(shí)現(xiàn)方法

瀏覽:96日期:2024-09-13 14:38:22
注冊功能實(shí)現(xiàn) forms組件進(jìn)行表單驗(yàn)證; 用戶頭像前端實(shí)時展示; ajax發(fā)送post請求;

應(yīng)用forms組件實(shí)現(xiàn)用戶輸入信息的校驗(yàn)。首先在app目錄下創(chuàng)建一個myform.py的文件。

如果你的項(xiàng)目至始至終只用到一個forms組件那么你可以直接建一個py文件書寫即可。

但是如果你的項(xiàng)目需要使用多個forms組件,那么你可以創(chuàng)建一個myforms文件夾在文件夾內(nèi),根據(jù)forms組件功能的不同創(chuàng)建不同的py文件。

regform.py loginform.py userform.py orderform.py

......

# 書寫針對用戶表的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ù)庫中校驗(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中配置注冊頁的路由信息。

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請求獲取數(shù)據(jù)、調(diào)用django orm功能存儲數(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’: ’[email protected]’} # 將校驗(yàn)通過的數(shù)據(jù)字典賦值給一個變量 clean_data = form_obj.cleaned_data # 將字典里面的confirm_password鍵值對刪除 clean_data.pop(’confirm_password’) # {’username’: ’zhangsan’, ’password’: ’123456’, ’email’: ’[email protected]’} # 注意用戶頭像是一個圖片的文件,request.POST中只有鍵值對的數(shù)據(jù) file_obj = request.FILES.get(’avatar’) ''' 針對用戶頭像一定要判斷是否傳值,不能直接添加到字典里面去 否則file_obj=None,會將數(shù)據(jù)庫中默認(rèn)的圖片路徑覆蓋。 ''' if file_obj:# 向字典數(shù)據(jù)clean_data中增加一個圖片頭像的字段clean_data[’avatar’] = file_obj # 操作數(shù)據(jù)庫保存數(shù)據(jù) models.UserInfo.objects.create_user(**clean_data) # 注冊成功則跳轉(zhuǎn)到登錄頁面 back_dic[’url’] = ’/login/’ else: back_dic[’code’] = 2000 # 校驗(yàn)存在錯誤 back_dic[’msg’] = form_obj.errors # 將字典類型的數(shù)據(jù)封裝成json返回到前端 return JsonResponse(back_dic) return render(request,’register.html’,locals())

前端的注冊頁面: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/[email protected]/dist/jquery.min.js'> <script src='https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js'></script> <title>用戶注冊</title></head><body><div class='container-fluid'> <div class='row'> <div class='col-md-8 col-md-offset-2'> <h1 class='text-center'>注冊</h1> <form id='myform'> <!--這里我們不用form表單提交數(shù)據(jù) 知識單純的用一下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='注冊' id='id_commit'> </form> </div> </div></div></body></html>

【重難點(diǎn)】在于書寫JS處理邏輯:包括了圖片上傳加載、ajax發(fā)送的post請求以及后端注冊結(jié)果的信息處理。

<script> $('#myfile').change(function () { // 文件閱讀器對象 // 1 先生成一個文件閱讀器對象 let myFileReaderObj = new FileReader(); // 2 獲取用戶上傳的頭像文件 let fileObj = $(this)[0].files[0]; // 3 將文件對象交給閱讀器對象讀取 myFileReaderObj.readAsDataURL(fileObj) // 異步操作 IO操作 // 4 利用文件閱讀器將文件展示到前端頁面 修改src屬性 // 等待文件閱讀器加載完畢之后再執(zhí)行 myFileReaderObj.onload = function(){ $(’#myimg’).attr(’src’,myFileReaderObj.result) } }) $(’#id_commit’).click(function () { // 發(fā)送ajax請求 我們發(fā)送的數(shù)據(jù)中即包含普通的鍵值也包含文件 let formDataObj = new FormData(); // 1.添加普通的鍵值對 {#console.log($(’#myform’).serializeArray()) // [{},{},{},{},{}] 只包含普通鍵值對#} $.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請求 $.ajax({ url:'', type:’post’, data:formDataObj, // 需要指定兩個關(guān)鍵性的參數(shù) contentType:false, processData:false, success:function (args) {if (args.code==1000){ // 跳轉(zhuǎn)到登陸頁面 //window.location.href = args.url}else{ // 如何將對應(yīng)的錯誤提示展示到對應(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注冊功能模塊實(shí)現(xiàn)方法

以上就是通用的Django注冊功能模塊實(shí)現(xiàn)步驟的詳細(xì)內(nèi)容,更多關(guān)于Django注冊功能模塊實(shí)現(xiàn)的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Django
相關(guān)文章:
主站蜘蛛池模板: 一级一片免费播放 | aaa在线| 特级毛片aaa免费版 特级毛片a级毛免费播放 | 日韩视频中文字幕 | 一本久道久久综合婷婷 | 欧美大片aaaa一级毛片 | 日韩免费一区二区三区在线 | 色老久久| 国产一二区 | 一级在线毛片 | 欧美成人777 | 成人在线黄色 | 亚洲 中文 欧美 日韩 在线人 | 国产精品自在自线亚洲 | 日本三级香港三级少妇 | 波多野结衣福利视频 | 亚洲综合久 | 手机看a| 国产区精品 | 欧美综合图片一区二区三区 | 亚州色吧| 国产中文字幕在线免费观看 | 国产99视频精品免费观看9e | 日韩毛片高清免费 | 男女视频在线观看免费高清观看 | 欧美性色生活片免费播放 | 欧美一级毛片免费高清的 | 岛国搬运工最新网地址 | 国产午夜a理论毛片在线影院 | 在线欧美精品一区二区三区 | 亚洲国产精品久久综合 | 亚洲三级视频在线观看 | 久久这里一区二区精品 | 欧美日韩中文字幕在线观看 | 三级毛片在线播放 | 欧美中日韩在线 | 国产精品深爱在线 | 国产91精品久久久久999 | 天天亚洲 | 91精品国产欧美一区二区 | 国产精选在线播放 |