濮阳杆衣贸易有限公司

主頁(yè) > 知識(shí)庫(kù) > 通用的Django注冊(cè)功能模塊實(shí)現(xiàn)方法

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

熱門(mén)標(biāo)簽:滴滴地圖標(biāo)注公司 如何申請(qǐng)400電話(huà)代理 甘肅高頻外呼系統(tǒng) 智能電話(huà)機(jī)器人調(diào)研 杭州房產(chǎn)地圖標(biāo)注 天津塘沽區(qū)地圖標(biāo)注 江門(mén)智能電話(huà)機(jī)器人 地圖標(biāo)注可以遠(yuǎn)程操作嗎 400電話(huà)在線(xiàn)如何申請(qǐng)

注冊(cè)功能實(shí)現(xiàn)

  • forms組件進(jìn)行表單驗(yàn)證;
  • 用戶(hù)頭像前端實(shí)時(shí)展示;
  • ajax發(fā)送post請(qǐng)求;

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

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

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

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

......

# 書(shū)寫(xiě)針對(duì)用戶(hù)表的forms主鍵代碼
from django import forms
from app01 import models

class MyRegForm(forms.Form):
  username = forms.CharField(label='用戶(hù)名',min_length=3,max_length=8,
                error_messages={
                  'required':'用戶(hù)名不能為空',
                  'min_length':'用戶(hù)名最少3位',
                  'max_length':'用戶(hù)名最大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)用戶(hù)名是否已存在
  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','用戶(hù)名已存在')
    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 admin
from django.urls import path
from app01 import views

urlpatterns = [
  path('admin/', admin.site.urls),
  path('register/',views.register,name='reg'),
]

在視圖函數(shù)views.py中編寫(xiě)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 MyRegForm
from app01 import models
from 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'}
      
      # 注意用戶(hù)頭像是一個(gè)圖片的文件,request.POST中只有鍵值對(duì)的數(shù)據(jù)
      file_obj = request.FILES.get('avatar')
      """
      	針對(duì)用戶(hù)頭像一定要判斷是否傳值,不能直接添加到字典里面去
      	否則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
    # 將字典類(lèi)型的數(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>用戶(hù)注冊(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 style="color: red" class="pull-right">/span>
          /div>
        {% endfor %}
        
        div class="form-group">
          label for="myfile">頭像
            {% load static %}
            img src="{% static 'img/default.jpg' %}" id='myimg' alt="" width="100" style="margin-left: 10px">
          /label>
          input type="file" id="myfile" name="avatar" style="display: none" >
        /div>

        input type="button" class="btn btn-primary pull-right" value="注冊(cè)" id="id_commit">
      /form>
    /div>
  /div>
/div>
/body>
/html>

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

script>
  $("#myfile").change(function () {
    // 文件閱讀器對(duì)象
    // 1 先生成一個(gè)文件閱讀器對(duì)象
    let myFileReaderObj = new FileReader();
    // 2 獲取用戶(hù)上傳的頭像文件
    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    ["用戶(hù)名不能為空"]#}
            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)注腳本之家其它相關(guān)文章!

您可能感興趣的文章:
  • django+vue實(shí)現(xiàn)注冊(cè)登錄的示例代碼
  • django注冊(cè)用郵箱發(fā)送驗(yàn)證碼的實(shí)現(xiàn)
  • Django怎么在admin后臺(tái)注冊(cè)數(shù)據(jù)庫(kù)表
  • Django用戶(hù)登錄與注冊(cè)系統(tǒng)的實(shí)現(xiàn)示例
  • django 框架實(shí)現(xiàn)的用戶(hù)注冊(cè)、登錄、退出功能示例
  • django實(shí)現(xiàn)用戶(hù)注冊(cè)實(shí)例講解
  • Django實(shí)現(xiàn)auth模塊下的登錄注冊(cè)與注銷(xiāo)功能
  • Python Django 實(shí)現(xiàn)簡(jiǎn)單注冊(cè)功能過(guò)程詳解
  • django的登錄注冊(cè)系統(tǒng)的示例代碼
  • django 通過(guò)ajax完成郵箱用戶(hù)注冊(cè)、激活賬號(hào)的方法
  • Django商城項(xiàng)目注冊(cè)功能的實(shí)現(xiàn)

標(biāo)簽:廊坊 臨汾 漢中 東莞 河池 德宏 長(zhǎng)春 重慶

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《通用的Django注冊(cè)功能模塊實(shí)現(xiàn)方法》,本文關(guān)鍵詞  通,用的,Django,注冊(cè),功能模塊,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《通用的Django注冊(cè)功能模塊實(shí)現(xiàn)方法》相關(guān)的同類(lèi)信息!
  • 本頁(yè)收集關(guān)于通用的Django注冊(cè)功能模塊實(shí)現(xiàn)方法的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    察隅县| 吉林市| 怀宁县| 平乐县| 同仁县| 吉木乃县| 武川县| 钟山县| 会宁县| 云和县| 濉溪县| 大石桥市| 扎兰屯市| 安达市| 五大连池市| 德庆县| 闸北区| 屯留县| 安西县| 阳西县| 龙州县| 侯马市| 太康县| 柏乡县| 泗洪县| 甘德县| 诏安县| 无棣县| 上栗县| 沾化县| 南充市| 祁连县| 洪洞县| 贵阳市| 蕲春县| 琼结县| 泰和县| 当涂县| 绥棱县| 盘山县| 望谟县|