Django中圖形驗證碼(django-simple-captcha)

django-simple-captcha

在網站開發的登陸頁面中,常常會須要使用到圖形驗證碼來驗證。在Django中,django-simple-captcha庫包提供了圖形驗證碼的使用。html

下面咱們來說講如何使用django-simple-captcha包來圖形驗證,而且點擊圖片刷新驗證碼。python

django-simple-captcha的安裝jquery

pip install django-simple-captcha

在settings.py文件中註冊captchagit

INSTALLED_APPS = [
    'captcha'
]

在settings.py文件中設置圖形驗證碼的樣式github

#字母驗證碼
CAPTCHA_IMAGE_SIZE = (80, 45)   # 設置 captcha 圖片大小
CAPTCHA_LENGTH = 4   # 字符個數
CAPTCHA_TIMEOUT = 1   # 超時(minutes)


#加減乘除驗證碼
CAPTCHA_OUTPUT_FORMAT = '%(image)s %(text_field)s %(hidden_field)s '
CAPTCHA_NOISE_FUNCTIONS = ('captcha.helpers.noise_null', 
     'captcha.helpers.noise_arcs', # 線
     'captcha.helpers.noise_dots', # 點
)
CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.random_char_challenge'
CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.math_challenge'
CAPTCHA_TIMEOUT = 1

執行數據遷移,在數據表中生成captcha_captchastore表ajax

python manage.py migrate

在urls.py中添加路由數據庫

urlpatterns = [
    path('captcha/', include('captcha.urls')),       # 圖片驗證碼 路由
    path('refresh_captcha/', views.refresh_captcha),    # 刷新驗證碼,ajax
]

下面是源代碼。 django

urls.py文件json

from django.urls import path
from django.conf.urls import include
from App.views import IndexView
from App import views

urlpatterns = [
    path('captcha/', include('captcha.urls')),
    path('refresh_captcha/',views.refresh_captcha),
    path('',IndexView.as_view()),
]

views.py文件bootstrap

from django.shortcuts import render
from django.views.generic import View
from captcha.models import CaptchaStore
from captcha.helpers import  captcha_image_url
from django.http import HttpResponse
import json

# 建立驗證碼
def captcha():
    hashkey = CaptchaStore.generate_key()   #驗證碼答案
    image_url = captcha_image_url(hashkey)  #驗證碼地址
    captcha = {'hashkey': hashkey, 'image_url': image_url}
    return captcha
#刷新驗證碼
def refresh_captcha(request):
    return HttpResponse(json.dumps(captcha()), content_type='application/json')
# 驗證驗證碼
def jarge_captcha(captchaStr, captchaHashkey):
    if captchaStr and captchaHashkey:
        try:
            # 獲取根據hashkey獲取數據庫中的response值
            get_captcha = CaptchaStore.objects.get(hashkey=captchaHashkey)
            if get_captcha.response == captchaStr.lower():     # 若是驗證碼匹配
                return True
        except:
            return False
    else:
        return False
class IndexView(View):
    def get(self, request):
        hashkey = CaptchaStore.generate_key()  # 驗證碼答案
        image_url = captcha_image_url(hashkey)  # 驗證碼地址
        captcha = {'hashkey': hashkey, 'image_url': image_url}
        return render(request, "login.html", locals())
    def post(self,request):
        capt=request.POST.get("captcha",None)         #用戶提交的驗證碼
        key=request.POST.get("hashkey",None)          #驗證碼答案
        if jarge_captcha(capt,key):
            return  HttpResponse("驗證碼正確")
        else:
            return HttpResponse("驗證碼錯誤")

login.html文件,這裏使用 js 動態刷新圖形驗證碼用到了jquery和bootstrap的js,因此,咱們提早將jquery和bootstrap放在了static文件夾下。關於如何加載靜態文件,傳送門——>Django加載靜態文件

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="{% static 'bower_components/jquery/dist/jquery.min.js' %}"></script>
    <script src="{% static 'bower_components/bootstrap/dist/js/bootstrap.min.js'%}"></script>
</head>
<body>
    <form action="/" method="post">
        <a href="#" class="captcha">
            <img src="{{ captcha.image_url }}" alt="點擊切換" id="id_captcha" >
        </a> <br>
        <input type="text" name="captcha" placeholder="驗證碼"> <br>
        <input value="{{ captcha.hashkey }}" name="hashkey" type="hidden" id="id_captcha_0">
        <button type="submit" class="btn btn-primary btn-block ">提交</button>
    </form>
<script>
        <!-- 動態刷新驗證碼js -->
        $(document).ready(function(){
            $('.captcha').click(function () {
                $.getJSON("refresh_captcha/", function (result) {
                    $('#id_captcha').attr('src', result['image_url']);
                    $('#id_captcha_0').val(result['hashkey'])
                });
            });
        });
</script>
</body>
</html>

參考文章:https://blog.csdn.net/qq_37648632/article/details/83149803

本文全部代碼:https://github.com/xie1997/Django_captcha

相關文章
相關標籤/搜索