在網站開發的登錄頁面中,經常會需要使用到圖形驗證碼來驗證。在Django中,django-simple-captcha庫包提供了圖形驗證碼的使用。
django-simple-captcha的安裝
pip instsall django-simple-captcha的安裝
在settings.py文件中注冊captcha
INSTALLED_APPS = [
'captcha'
]
在settings.py文件中設置圖形驗證碼的樣式
#字母驗證碼
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表
python manage.py migrate
在urls.py中添加路由
urlpatterns = [
path('captcha/', include('captcha.urls')), # 圖片驗證碼 路由
path('refresh_captcha/', views.refresh_captcha), # 刷新驗證碼,ajax
]
示例
urls.py文件
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文件
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文件
{% 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>

擴展JavaScript
#這樣子設置的background-image就是url(s),JavaScript代碼當中的s變量並沒有如你期望的那樣子擴展開來。對JavaScript的運用不熟悉。
var s = "images/" + row + ".jpg";//row是table的當前行
$("body").css("background-image","url(" + s + ")");