欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2021年02月05日 11:26:22   作者:TrainingL  
這篇文章主要介紹了通用的Django注冊功能模塊實(shí)現(xiàn)步驟,幫助大家更好的理解和使用django,感興趣的朋友可以了解下

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

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

應(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

......

# 書寫針對用戶表的forms主鍵代碼
from django import forms
from app01 import models

class 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 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中編寫forms組件檢驗(yàn)、ajax發(fā)送的post請求獲取數(shù)據(jù)、調(diào)用django orm功能存儲數(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)通過的數(shù)據(jù)字典賦值給一個(gè)變量
      clean_data = form_obj.cleaned_data 
      # 將字典里面的confirm_password鍵值對刪除
      clean_data.pop('confirm_password') # {'username': 'zhangsan', 'password': '123456', 'email': '123@qq.com'}
      
      # 注意用戶頭像是一個(gè)圖片的文件,request.POST中只有鍵值對的數(shù)據(jù)
      file_obj = request.FILES.get('avatar')
      """
      	針對用戶頭像一定要判斷是否傳值,不能直接添加到字典里面去
      	否則file_obj=None,會將數(shù)據(jù)庫中默認(rèn)的圖片路徑覆蓋。
      """
      if file_obj:
        # 向字典數(shù)據(jù)clean_data中增加一個(gè)圖片頭像的字段
        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)存在錯(cuò)誤
      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/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>用戶注冊</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 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="注冊" id="id_commit">
      </form>
    </div>
  </div>
</div>
</body>
</html>

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

<script>
  $("#myfile").change(function () {
    // 文件閱讀器對象
    // 1 先生成一個(gè)文件閱讀器對象
    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,

      // 需要指定兩個(gè)關(guān)鍵性的參數(shù)
      contentType:false,
      processData:false,

      success:function (args) {
        if (args.code==1000){
          // 跳轉(zhuǎn)到登陸頁面
          //window.location.href = args.url
        }else{
          // 如何將對應(yīng)的錯(cuò)誤提示展示到對應(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)步驟的詳細(xì)內(nèi)容,更多關(guān)于Django注冊功能模塊實(shí)現(xiàn)的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 五分鐘學(xué)會Python 模塊和包、文件

    五分鐘學(xué)會Python 模塊和包、文件

    通過學(xué)習(xí)本文可以五分鐘掌握Python 模塊和包、文件的相關(guān)知識,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-08-08
  • 淺談Pytorch中的torch.gather函數(shù)的含義

    淺談Pytorch中的torch.gather函數(shù)的含義

    今天小編就為大家分享一篇淺談Pytorch中的torch.gather函數(shù)的含義,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • 詳解Python中pyautogui庫的最全使用方法

    詳解Python中pyautogui庫的最全使用方法

    這篇文章主要介紹了詳解Python中pyautogui庫的最全使用方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-04-04
  • python中將zip壓縮包轉(zhuǎn)為gz.tar的方法

    python中將zip壓縮包轉(zhuǎn)為gz.tar的方法

    今天小編就為大家分享一篇python中將zip壓縮包轉(zhuǎn)為gz.tar的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-10-10
  • Python Matplotlib繪制箱型圖(箱線圖)boxplot的方法詳解

    Python Matplotlib繪制箱型圖(箱線圖)boxplot的方法詳解

    箱線圖(箱型圖)主要作用是發(fā)現(xiàn)數(shù)據(jù)內(nèi)部整體的分布分散情況,包括上下限、各分位數(shù)、異常值等,本文為大家整理了Matplotlib繪制箱型圖的所以方法,希望對大家有所幫助
    2023-05-05
  • python機(jī)器學(xué)習(xí)實(shí)戰(zhàn)之最近鄰kNN分類器

    python機(jī)器學(xué)習(xí)實(shí)戰(zhàn)之最近鄰kNN分類器

    這篇文章主要介紹了python機(jī)器學(xué)習(xí)實(shí)戰(zhàn)之最近鄰kNN分類器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-12-12
  • Python操作列表的常用方法分享

    Python操作列表的常用方法分享

    這篇文章主要介紹了Python操作列表的常用方法,需要的朋友可以參考下
    2014-02-02
  • Opencv中cv2.cvtColor彩色圖轉(zhuǎn)灰度圖的其他6種方法

    Opencv中cv2.cvtColor彩色圖轉(zhuǎn)灰度圖的其他6種方法

    本文主要介紹了Opencv中cv2.cvtColor彩色圖轉(zhuǎn)灰度圖的其他6種方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-05-05
  • Python實(shí)現(xiàn)Word的讀寫改操作

    Python實(shí)現(xiàn)Word的讀寫改操作

    本文主要介紹了運(yùn)用docx模塊實(shí)現(xiàn)讀取Word,調(diào)整Word樣式以及Word 寫入操作的示例代碼,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-11-11
  • 教你怎么用Python實(shí)現(xiàn)自動生日祝福

    教你怎么用Python實(shí)現(xiàn)自動生日祝福

    這篇文章主要介紹了教你怎么用Python實(shí)現(xiàn)自動生日祝福,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)python的小伙伴們有很好地幫助,需要的朋友可以參考下
    2021-05-05

最新評論