- 安装:django-simple-captcha
- 在settings.py文件app注册captcha: ‘captcha’
- 在settings.py文件设置验证码图片样式:
CAPTCHA_IMAGE_SIZE = (80, 45)
CAPTCHA_LENGTH = 4
CAPTCHA_TIMEOUT = 1
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
- 数据迁移:python manage.py migrate
- 在urls.py配置路由器:
url(r'captcha',include('captcha.urls')),#验证码
- 选择app配置路由’url(‘refresh_captcha/’, refresh_captcha,name = ‘refresh_captcha’), # 刷新验证码,ajax’
- 编写视图函数
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:
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("验证码错误")
- 前端页面代码
{% 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>
参考