django搭建BBS-登入&驗證碼的生成

来源:https://www.cnblogs.com/pythonywy/archive/2019/08/25/11408318.html
-Advertisement-
Play Games

django搭建BBS 登入&驗證碼的生成 文件結構 app 介面 migrations _\_inint\_\_.py admin.py apps.py bbsform.py models.py tests.py views.py avatar BBS \_\_inint\_\_.py setti ...


django搭建BBS-登入&驗證碼的生成

基於註冊完成後

文件結構

  • app 介面
    • migrations
    • __inint__.py
    • admin.py 管理員頁面註冊表單用
    • apps.py
    • bbsform.py form組件相關設置
    • models.py 模型存放
    • tests.py
    • views.py 業務邏輯
  • avatar 圖片文件存儲
  • BBS 項目名稱以及路由存放
    • __inint__.py
    • settings.py
    • urls.py
    • wsgi.py
  • static
    • bootstrap-3.3.7-dist bootstrap文件網上下載的
    • jquery-3.4.1.min.js jq文件
  • templates 頁面文件存放

一.創建圖片驗證

1.路由

urls.py

from django.conf.urls import url
from django.contrib import admin
#主路由導入視圖內函數
from app import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^register/', views.register),
    url(r'^login/', views.login),
    url(r'^get_code/', views.get_code),
]

2.邏輯業務

views.py

from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse
#Image導入
#ImageDraw在圖片上寫字
#ImageFont 寫字的格式
from PIL import Image,ImageDraw,ImageFont
import random
# 相當於把文件以byte格式存到記憶體中
from io import BytesIO

from django.contrib import auth

from app.bbsforms import Register
from app import models

from django.db.models import Count
from django.db.models.functions import TruncMonth
from django.db.models import F





# Create your views here.
def register(request):
    if request.method=='GET':
        form=Register()
        return render(request,'register.html',{'form':form})
    elif request.is_ajax():
        response={'code':100,'msg':None}
        form = Register(request.POST)
        if form.is_valid():
            #校驗通過的數據
            clean_data=form.cleaned_data
            #把re_pwd剔除
            clean_data.pop('re_pwd')
            #取出頭像
            avatar=request.FILES.get('avatar')
            if avatar:
                #因為用的是FileField,只需要把文件對象賦值給avatar欄位,自動做保存
                clean_data['avatar']=avatar
            user=models.UserInfo.objects.create_user(**clean_data)
            if user:
                response['msg'] = '創建成功'
            else:
                response['code'] = 103
                # 把校驗不通過的數據返回
                response['msg'] = '創建失敗'
        else:
            response['code']=101
            #把校驗不通過的數據返回
            response['msg']=form.errors
            print(type(form.errors))
        return JsonResponse(response,safe=False)


def login(request):
    if request.method=='GET':
        return render(request,'login.html')


def get_code(request):
    if request.method == 'GET':
        img = Image.new('RGB', (350, 40), (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
        # 寫文字
        # 生成一個字體對象
        font = ImageFont.truetype('/static/Gabriola.ttf', 34)
        # 調用方法,返回一個畫板對象
        draw = ImageDraw.Draw(img)

        new_text =''
        # 生成隨機8位數字
        for x_index in range(1, 8):
            num = chr(random.randint(48, 57))
            word = chr(random.randint(65, 90))
            word_1 = chr(random.randint(97, 122))
            text =random.choice((num, word, word_1))
            draw.text((x_index * 32, 0),text, font=font)
            new_text +=text

        # 加點線
        width = 320
        height = 35
        for i in range(5):
            x1 = random.randint(0, width)
            x2 = random.randint(0, width)
            y1 = random.randint(0, height)
            y2 = random.randint(0, height)
            # 在圖片上畫線
            draw.line((x1, y1, x2, y2), fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))

        for i in range(33):
            # 畫點
            draw.point([random.randint(0, width), random.randint(0, height)], fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
            x = random.randint(0, width)
            y = random.randint(0, height)
            # 畫弧形
            draw.arc((x, y, x + 4, y + 4), 0, 90, fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
        print(new_text)
        #存在session中
        request.session['code']=new_text
        #存記憶體
        f = BytesIO()
        img.save(f, 'png')
        return HttpResponse(f.getvalue())

3.網頁

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    {% include 'bootstrap.html' %}<--載入bootstrap-->
    <meta charset="UTF-8">
    <title>登入</title>
</head>
<body>
<div class="container-fluid center-block">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <h1>登陸</h1>
            <form action="">
                <div class="form-group">
                    <label for="id_name">用戶名</label>
                    <input type="text" name="name" id="id_name" class="form-control">
                </div>
                <div class="form-group">
                    <label for="pwd">密碼</label>
                    <input type="password" name="pwd" id="pwd" class="form-control">
                </div>
                <div class="form-group">
                    <label for="id_code">驗證碼</label>
                    <div class="row">
                        <div class="col-md-6">
                            <input type="text" name="code" id="id_code" class="form-control">
                        </div>
                        <div class="col-md-6" id="img">
                            <img src="/get_code/" height="40" width="350" class="img-code">
                        </div>
                    </div>
                </div>
                <input type="submit" value="提交" class="btn-success">
            </form>
        </div>
    </div>
</div>
</body>
{% include 'jq.html' %} <--載入jq-->
<script>  <--利用img標標簽屬性src發送改變後會自己去找-->
    $('.img-code').click(function () {
        var img_code_src = $(this).attr('src');
        img_code_src += '1';
        console.log(img_code_src);
        $(this).attr('src',img_code_src)
    })
</script>
</html>

二.賬號信息進行驗證

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    {% include 'bootstrap.html' %}
    <meta charset="UTF-8">
    <title>登入</title>
</head>
<body>
<div class="container-fluid center-block">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            {% csrf_token %}
            <h1>登陸</h1>
            <form action="">
                <div class="form-group">
                    <label for="id_name">用戶名</label>
                    <input type="text" name="name" id="id_name" class="form-control">
                </div>
                <div class="form-group">
                    <label for="pwd">密碼</label>
                    <input type="password" name="pwd" id="pwd" class="form-control">
                </div>
                <div class="form-group">
                    <label for="id_code">驗證碼</label>
                    <div class="row">
                        <div class="col-md-6">
                            <input type="text" name="code" id="id_code" class="form-control">
                        </div>
                        <div class="col-md-6" id="img">
                            <img src="/get_code/" height="40" width="350" class="img-code">
                        </div>
                    </div>
                </div>
                <input type="button" value="提交" class="btn-success" id="up_data">
                <span style="color: red" id="msg"></span>
            </form>
        </div>
    </div>
</div>
</body>
{% include 'jq.html' %}
<script>
    $('.img-code').click(function () {
        var img_code_src = $(this).attr('src');
        img_code_src += '1';
        console.log(img_code_src);
        $(this).attr('src',img_code_src)
    })
</script>


<script>
    $('#up_data').click(function () {
        $.ajax({
            type:'post',
            url:'/login/',
            data:{'name':$('#id_name').val(),
                'pwd':$('#pwd').val(),
                'code':$('#id_code').val(),
                'csrfmiddlewaretoken':'{{csrf_token}}'
            },
            success:function (msg) {
                console.log(msg);
                $('#msg').text(msg);
                if (msg =='登入成功'){
                    console.log('sb');
                    window.location.replace('http://www.baidu.com');<--暫時先放百度-->
                }
            }
        })
    })
</script>
</html>

views.py

from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse
#Image導入
#ImageDraw在圖片上寫字
#ImageFont 寫字的格式
from PIL import Image,ImageDraw,ImageFont
import random
# 相當於把文件以byte格式存到記憶體中
from io import BytesIO

from django.contrib import auth

from app.bbsforms import Register
from app import models

from django.db.models import Count
from django.db.models.functions import TruncMonth
from django.db.models import F





# Create your views here.
def register(request):
    if request.method=='GET':
        form=Register()
        return render(request,'register.html',{'form':form})
    elif request.is_ajax():
        response={'code':100,'msg':None}
        form = Register(request.POST)
        if form.is_valid():
            #校驗通過的數據
            clean_data=form.cleaned_data
            #把re_pwd剔除
            clean_data.pop('re_pwd')
            #取出頭像
            avatar=request.FILES.get('avatar')
            if avatar:
                #因為用的是FileField,只需要把文件對象賦值給avatar欄位,自動做保存
                clean_data['avatar']=avatar
            user=models.UserInfo.objects.create_user(**clean_data)
            if user:
                response['msg'] = '創建成功'
            else:
                response['code'] = 103
                # 把校驗不通過的數據返回
                response['msg'] = '創建失敗'
        else:
            response['code']=101
            #把校驗不通過的數據返回
            response['msg']=form.errors
            print(type(form.errors))
        return JsonResponse(response,safe=False)


def login(request):
    if request.method=='GET':
        return render(request,'login.html')
    else:
        print(request.POST)
        user_name=request.POST.get('name')
        pwd=request.POST.get('pwd')
        code=request.POST.get('code')

        user=auth.authenticate(username=user_name,password=pwd)
        print(user)
        if request.session.get('code').upper() !=code.upper(): #忽略大小寫
            return HttpResponse('驗證碼錯誤')
        elif not user:
            return HttpResponse('賬號密碼錯誤')
        else:
            return HttpResponse('登入成功')



def get_code(request):
    if request.method == 'GET':
        img = Image.new('RGB', (350, 40), (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
        # 寫文字
        # 生成一個字體對象
        font = ImageFont.truetype('/static/Gabriola.ttf', 34)
        # 調用方法,返回一個畫板對象
        draw = ImageDraw.Draw(img)

        new_text =''
        # 生成隨機8位數字
        for x_index in range(1, 8):
            num = chr(random.randint(48, 57))
            word = chr(random.randint(65, 90))
            word_1 = chr(random.randint(97, 122))
            text =random.choice((num, word, word_1))
            draw.text((x_index * 32, 0),text, font=font)
            new_text +=text

        # 加點線
        width = 320
        height = 35
        for i in range(5):
            x1 = random.randint(0, width)
            x2 = random.randint(0, width)
            y1 = random.randint(0, height)
            y2 = random.randint(0, height)
            # 在圖片上畫線
            draw.line((x1, y1, x2, y2), fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))

        for i in range(33):
            # 畫點
            draw.point([random.randint(0, width), random.randint(0, height)], fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
            x = random.randint(0, width)
            y = random.randint(0, height)
            # 畫弧形
            draw.arc((x, y, x + 4, y + 4), 0, 90, fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
        print(new_text)
        #存在session中
        request.session['code']=new_text
        #存記憶體
        f = BytesIO()
        img.save(f, 'png')
        return HttpResponse(f.getvalue())

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 自動登錄勾選提示效果 要求:滑鼠移入顯示提示信息框;滑鼠離開,信息框消失,消失的效果延遲 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="w ...
  • ``` ``` ...
  • reduce(收斂):接收一個回調函數作為累加器,數組中的每個值(從左到右)開始縮減,最終為一個值,是ES5中新增的又一個數組逐項處理方法。 reduce(callback,initialValue) callback(一個在數組中每一項上調用的函數,接受四個函數:) previousValue(上 ...
  • 簡易萬年曆這個案例是比較有意義的,雖然是個小demo,但涵蓋的知識是一點也不少啊!需要靜下心來好好理解,完全理解下來,就會覺得也沒那麼難,理解了這個demo,後續很多東西都知道怎麼寫了。好啦,先上HTMl部分的代碼。 樣式可以自己更改哈! 下麵是javascript的代碼,會加上註釋,以防小白白看不 ...
  • React 中 setState()詳細解讀 對於 setState() 相信伙伴們都用過,它是 React 官方推薦用來更新組件 state 的 API,但是對於 setState() 你真的瞭解嗎?且待我慢慢詳聊一番。 setState() 官方用法指南 語法1: updater:函數類型,返回 ...
  • js中\=\=和\=\=\=區別 簡單來說: \=\= 代表相同, \=\=\=代表嚴格相同, 為啥這麼說呢, 這麼理解: 當進行雙等號比較時候: 先檢查兩個操作數數據類型,如果相同, 則進行\=\=\=比較, 如果不同, 則願意為你進行一次類型轉換, 轉換成相同類型後再進行比較, 而===比較時, ...
  • jQuery跳轉到另一個頁面 1.我們可以利用http的重定向來跳轉 window.location.replace(" "https://www.cnblogs.com/pythonywy/" "); 2.使用href來跳轉 window.location.href = " "https://ww ...
  • html 基礎標簽 單標簽 1.註釋標簽: <! 註釋信息 看不到 ctrl+/ <! 網頁頭部導航盒子 換行標簽: 橫線標簽: 標題標簽: 段落標簽: 表示強調標簽: 文字 屬性:文字加顏色 color:改變文字顏色 size:改文字大小屬性 例如:文字 文本加粗顯示:或者 文字斜體顯示: 或 下 ...
一周排行
    -Advertisement-
    Play Games
  • 概述:在C#中,++i和i++都是自增運算符,其中++i先增加值再返回,而i++先返回值再增加。應用場景根據需求選擇,首碼適合先增後用,尾碼適合先用後增。詳細示例提供清晰的代碼演示這兩者的操作時機和實際應用。 在C#中,++i 和 i++ 都是自增運算符,但它們在操作上有細微的差異,主要體現在操作的 ...
  • 上次發佈了:Taurus.MVC 性能壓力測試(ap 壓測 和 linux 下wrk 壓測):.NET Core 版本,今天計劃準備壓測一下 .NET 版本,來測試並記錄一下 Taurus.MVC 框架在 .NET 版本的性能,以便後續持續優化改進。 為了方便對比,本文章的電腦環境和測試思路,儘量和... ...
  • .NET WebAPI作為一種構建RESTful服務的強大工具,為開發者提供了便捷的方式來定義、處理HTTP請求並返迴響應。在設計API介面時,正確地接收和解析客戶端發送的數據至關重要。.NET WebAPI提供了一系列特性,如[FromRoute]、[FromQuery]和[FromBody],用 ...
  • 原因:我之所以想做這個項目,是因為在之前查找關於C#/WPF相關資料時,我發現講解圖像濾鏡的資源非常稀缺。此外,我註意到許多現有的開源庫主要基於CPU進行圖像渲染。這種方式在處理大量圖像時,會導致CPU的渲染負擔過重。因此,我將在下文中介紹如何通過GPU渲染來有效實現圖像的各種濾鏡效果。 生成的效果 ...
  • 引言 上一章我們介紹了在xUnit單元測試中用xUnit.DependencyInject來使用依賴註入,上一章我們的Sample.Repository倉儲層有一個批量註入的介面沒有做單元測試,今天用這個示例來演示一下如何用Bogus創建模擬數據 ,和 EFCore 的種子數據生成 Bogus 的優 ...
  • 一、前言 在自己的項目中,涉及到實時心率曲線的繪製,項目上的曲線繪製,一般很難找到能直接用的第三方庫,而且有些還是定製化的功能,所以還是自己繪製比較方便。很多人一聽到自己畫就害怕,感覺很難,今天就分享一個完整的實時心率數據繪製心率曲線圖的例子;之前的博客也分享給DrawingVisual繪製曲線的方 ...
  • 如果你在自定義的 Main 方法中直接使用 App 類並啟動應用程式,但發現 App.xaml 中定義的資源沒有被正確載入,那麼問題可能在於如何正確配置 App.xaml 與你的 App 類的交互。 確保 App.xaml 文件中的 x:Class 屬性正確指向你的 App 類。這樣,當你創建 Ap ...
  • 一:背景 1. 講故事 上個月有個朋友在微信上找到我,說他們的軟體在客戶那邊隔幾天就要崩潰一次,一直都沒有找到原因,讓我幫忙看下怎麼回事,確實工控類的軟體環境複雜難搞,朋友手上有一個崩潰的dump,剛好丟給我來分析一下。 二:WinDbg分析 1. 程式為什麼會崩潰 windbg 有一個厲害之處在於 ...
  • 前言 .NET生態中有許多依賴註入容器。在大多數情況下,微軟提供的內置容器在易用性和性能方面都非常優秀。外加ASP.NET Core預設使用內置容器,使用很方便。 但是筆者在使用中一直有一個頭疼的問題:服務工廠無法提供請求的服務類型相關的信息。這在一般情況下並沒有影響,但是內置容器支持註冊開放泛型服 ...
  • 一、前言 在項目開發過程中,DataGrid是經常使用到的一個數據展示控制項,而通常表格的最後一列是作為操作列存在,比如會有編輯、刪除等功能按鈕。但WPF的原始DataGrid中,預設只支持固定左側列,這跟大家習慣性操作列放最後不符,今天就來介紹一種簡單的方式實現固定右側列。(這裡的實現方式參考的大佬 ...