django验证码模块django-simple-captcha的使用介绍
django-simple-captcha是django验证码模块,非常方便易用。
1、环境的准备:
在django项目环境中安装:pip install django-simple-captcha
django-simple-captcha官方文档地址:http://django-simple-captcha.readthedocs.io/en/latest/
2、配置settings.py:
# 注册app
INSTALLED_APPS = [
...,
'captcha',
]
# django_simple_captcha 验证码配置其他配置项查看文档
# 默认格式
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', # 点
)
# 图片中的文字为随机英文字母,如 mdsh
# CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.random_char_challenge'
# 图片中的文字为数字表达式,如2+2=
CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.math_challenge'
# 超时(minutes)
CAPTCHA_TIMEOUT = 1
执行migrate命令,生成CaptchaStore表,表中主要有chalenge,response,hashkey三个字段,分别存放验证码、验证码的值、key。
3、配置urls.py:
urlpatterns = [
path(r'^captcha/', include('captcha.urls')), # 验证码url, 内部使用了路由分发
path(r'^login/', views.login, name='login'), # 登录url
]
4、配置form.py:
from django import forms
from captcha.fields import CaptchaField class CaptachTestForm(forms.Form):
username=forms.CharField(label='username')
password=forms.CharField(label='password',widget=forms.PasswordInput)
captcha=CaptchaField()
form中captcha的html代码为:
<tr><th><label for="id_captcha_1">Captcha:</label></th><td>
<img src="/captcha/image/496c83bf8bf85c313894e27797205b074cd9c263/" alt="captcha" class="captcha" /> <input autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false" id="id_captcha_1" name="captcha_1" type="text" />
<input id="id_captcha_0" name="captcha_0" type="hidden" value="496c83bf8bf85c313894e27797205b074cd9c263" />
</td></tr>
分别为验证码图片、验证码input框、key值的隐藏input框,即通过返回到后台的key值到数据表CaptchaStore中查找验证码的reponse值进行验证。
5、配置views.py:
from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import login,authenticate
from django.http import JsonResponse
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url
from .forms import CaptachTestForm def loginView(request):
# hashkey验证码生成的秘钥,image_url验证码的图片地址
hashkey = CaptchaStore.generate_key()
image_url = captcha_image_url(hashkey)
if request.method=='POST':
form=CaptachTestForm(request.POST)
if form.is_valid():
username=form.cleaned_data['username']
password=form.cleaned_data['password']
if User.objects.filter(username=username):
user=authenticate(username=username,password=password)
if user:
if user.is_active:
login(request,user)
tips='login success'
return render(request,'homePage.html')
else:
tips='the auth is wrongs,please input again...'
else:
tips='the username is not found,please to registe...'
else:
form=CaptachTestForm()
return render(request,'account/loginpage.html', locals()) def ajax_val(request):
if request.is_ajax():
r=request.GET['response']
h=request.GET['hashkey']
cs=CaptchaStore.objects.filter(response=r,hashkey=h)
if cs:
json_data={'status':1}
else:
json_data={'status':0}
return JsonResponse(json_data)
else:
json_data={'status':0}
return JsonResponse(json_data)
6、html 模板中显示验证码
<div class="form-group">
<label class="col-md-5 control-label" >captcha</label>
<div class="col-md-2 text-left"> <!-- {{ form.captcha }} </div> -->
<input autocomplete="off" id="id_captcha_1" name="captcha_1" type="text" style="width:80px;height: 28px">
<img src="{{ image_url}}" alt="captcha" class="captcha">
<input id="id_captcha_0" name="captcha_0" type="hidden" value="{{ hashkey }}"> </div>
</div>
在模板中加入js代码,使用ajax刷新验证码
<script>
$(function (){
$('.captcha').click(function (){
// console.log('click');
$.getJSON("/captcha/refresh/",function (result){
$('.captcha').attr('src',result['image_url']);
$('#id_captcha_0').val(result['key'])
})
});
$('#id_captcha_1').blur(function (){
json_data={
'response':$('#id_captcha_1').val(),
'hashkey':$('#id_captcha_0').val()
}
$.getJSON('/account/ajax_val',json_data,function (data){
$('#captcha_status').remove()
if(data['status']){
$('#id_captcha_1').after('<span id="captcha_status">*验证码正确</span>')
}else {
$('#id_captcha_1').after('<span id="captcha_status">*验证码错误</span>')
}
});
});
});
</script>
7、使用效果:

8、小结:
django-simple-captcha在数据库生成数据表CaptchaStore,设立chalenge,response,hashkey三个字段,分别存放验证码、验证码的值、key。
froms.py设置captcha字段,forms中的html代码中有三个标签,分别是img、验证码的input、key的input。通过key查找response值验证验证码。
可以参考https://www.cnblogs.com/the3times/p/13124453.html,此文介绍的较为详细。
django验证码模块django-simple-captcha的使用介绍的更多相关文章
- Django Simple Captcha插件
正文开始 先看官方描述 1.安装 打开控制台,输入如下: pip install django-simple-captcha 2.把APP添加到Django项目进入自己的Django项目,在setti ...
- Django Simple Captcha的使用
Django Simple Captcha的使用 1.下载Django Simple Captcha django-simple-captcha官方文档地址 http://django-simple- ...
- 探索Django验证码功能的实现 - DjangoStarter项目模板里的封装
前言 依然是最近在做的这个项目,用Django做后端,App上提交信息的时候需要一个验证码来防止用户乱提交,正好我的「DjangoStarter」项目脚手架也有封装了验证码功能,不过我发现好像里面只是 ...
- django 验证码
1.django 缓存设置 django的六种缓存(mysql+redis) :https://www.cnblogs.com/xiaonq/p/7978402.html#i6 1.1 安装Djang ...
- django日志,django-crontab,django邮件模块
django 日志 四大块,格式器,过滤器,处理器,日志管理器 LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatt ...
- django验证码django-simple-captha
搭建网站很经常要用到验证码,django中就有这样的中间件django-simple-captha githup地址https://github.com/mbi/django-simple-captc ...
- django 验证码(django-simple-captcha)
django 验证码(django-simple-captcha) django-simple-captcha 官方文档(含基于modelForm的用法) https://django-simple ...
- Python Django 功能模块
Python Django模块 Django模块,是针对有django基础,对django功能进行模块化,方便下次使用. 一.注册模块 该注册采用邮箱验证,注册成功后会发送激活链接到邮箱. 邮箱验证参 ...
- Django学习之六:Django 常用模块导入记忆
Django 常用模块导入记忆 django相关 1. urls相关操作 from django.urls import path, re_path, include from django.urls ...
- Python第十三天 django 1.6 导入模板 定义数据模型 访问数据库 GET和POST方法 SimpleCMDB项目 urllib模块 urllib2模块 httplib模块 django和web服务器整合 wsgi模块 gunicorn模块
Python第十三天 django 1.6 导入模板 定义数据模型 访问数据库 GET和POST方法 SimpleCMDB项目 urllib模块 urllib2模块 ...
随机推荐
- windows与linux下的路径区别
windows与linux下的路径区别windows用的是"\",linux用的是"/"这一点要特别清楚,, ps:在PHP windows也可以用/表示路径 ...
- Android中添加set文件
一般情况下,set文件在anim目录下面,如果没有anim目录,就新建一个. 1. 右键点击anim,选择new->Animation Resource File 2. 选择类型为set,点击O ...
- c++练习267题 火柴棒等式
*267题 原题传送门:http://oj.tfls.net/p/267 题解: #include<bits/stdc++.h>using namespace std;int c,m;in ...
- 2022-05-13内部群每日三题-清辉PMP
1.一个运营团队认为他们的技能在项目上是不必要的,团队士气低落,且团队成员试图阻止项目实现目标.项目经理应该怎么做? A.建议公司改变战略,并立即停止项目 B.要求工会的支持来激励团队 C.根据项目成 ...
- Excel之VLOOKUP()函数的基本用法
语法: VLOOKUP(lookup_value,table_array,col_index_num,[range_lookup]) 规则: 注意: 查找的值:内容需要完全一样 查找范围:查找范围的 ...
- 蓝牙mesh组网实践(mesh组网的评估与沁恒蓝牙芯片选型)
目录 沁恒的组网方式主要有2.4G私有协议组网和BLE mesh组网两大类.2.4G私有协议组网灵活性相对较高,对开发者的要求也相对较高.mesh组网本身有一系列规范,考虑到了可靠性.安全性.功能性等 ...
- 《CSOL大灾变》开发记录——武器购买逻辑开发
上次完成了武器购买界面设计,这次来完成武器购买逻辑与武器选择逻辑. 武器购买逻辑分为两个部分,一个部分是GUI部分的逻辑,也就是购买菜单,一个是武器游戏数据更新的逻辑,也就是实际中玩家获取武器的逻辑开 ...
- Python爬取三国演义章节标题和内容(bs4爬取,解决中文乱码)
import os.path import requests from bs4 import BeautifulSoup if __name__ == '__main__': if not os.pa ...
- Unity模型剖切
效果展示 1.首先先下载一个模型剖切插件Cross-Section插件 没有的下方链接自取 插件下载链接 2.下载之后导入到项目 导入之后的样子如下图 因项目需求需要剖切模型,要使用滑动条进行剖切, ...
- mysql8改密码
登录后执行语句 ALTER USER 'test'@'localhost' IDENTIFIED WITH MYSQL_NATIVE_PASSWORD BY '新密码'; 修改Host范围 updat ...