1.安装django-simple-captcha

pip install django-simple-captcha

2.配置settings.py

##加app列表
INSTALLED_APPS =[
# 校验码
'captcha',
]
## django_simple_captcha 验证码配置 # 格式
CAPTCHA_OUTPUT_FORMAT = u'%(text_field)s %(hidden_field)s %(image)s' # 字体倾斜度
CAPTCHA_LETTER_ROTATION = (-70, 35) # 噪点样式
CAPTCHA_NOISE_FUNCTIONS = (
# 'captcha.helpers.noise_null', # 没有样式
'captcha.helpers.noise_arcs', # 线
'captcha.helpers.noise_dots', # 点
) # 图片大小
CAPTCHA_IMAGE_SIZE = (90, 25)
CAPTCHA_BACKGROUND_COLOR = '#ffffff'
CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.random_char_challenge' # 图片中的文字为随机英文字母,如 mdsh
# CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.math_challenge' # 图片中的文字为数字表达式,如1+2=</span> CAPTCHA_LENGTH = 4 # 字符个数
CAPTCHA_TIMEOUT = 3 # 超时时间(minutes),默认为5分钟
# 是否测试模式,测试模式下输入任何字符都可通过
CAPTCHA_TEST_MODE = False # CAPTCHA_MATH_CHALLENGE_OPERATOR='math_challenge'

 3.迁移数据库

# 生成迁移文件
python manage.py makemigrations
# 生成数据表
python manage.py migrate

  迁移成功后,数据库生成captcha_captchastore表,models.py如下

class CaptchaStore(models.Model):
challenge = models.CharField(blank=False, max_length=32) # 验证码
response = models.CharField(blank=False, max_length=32) # 验证码,回复时验证
hashkey = models.CharField(blank=False, max_length=40, unique=True) # 唯一标识key
expiration = models.DateTimeField(blank=False) # 过期时间 def save(self, *args, **kwargs):
self.response = self.response.lower()
if not self.expiration:
self.expiration = get_safe_now() + datetime.timedelta(minutes=int(captcha_settings.CAPTCHA_TIMEOUT))
if not self.hashkey:
key_ = (
smart_text(randrange(0, MAX_RANDOM_KEY)) +
smart_text(time.time()) +
smart_text(self.challenge, errors='ignore') +
smart_text(self.response, errors='ignore')
).encode('utf8')
self.hashkey = hashlib.sha1(key_).hexdigest()
del(key_)
super(CaptchaStore, self).save(*args, **kwargs) def __unicode__(self):
return self.challenge def remove_expired(cls):
cls.objects.filter(expiration__lte=get_safe_now()).delete()
remove_expired = classmethod(remove_expired) @classmethod
def generate_key(cls):
challenge, response = captcha_settings.get_challenge()() # 生成验证码
store = cls.objects.create(challenge=challenge, response=response) # 验证码存库 return store.hashkey

4.urls.py配置

urlpatterns += [
url(r'^captcha/', include('captcha.urls')),
]

 5.forms.py

from django import forms
from maiziedu.models import UserProfile
from captcha.fields import CaptchaField class RegisterForm(forms.Form):
'''
注册
'''
username = forms.EmailField(widget=forms.TextInput(
                  attrs={"class": "form-control", "placeholder": "请输入邮箱账号", "value": "", "required": "required",}),
max_length=50,error_messages={"required": "用户名不能为空",})
password = forms.CharField(widget=forms.PasswordInput(
                  attrs={"class": "form-control", "placeholder": "请输入密码", "value": "", "required": "required",}),
min_length=8, max_length=50,error_messages={"required": "密码不能为空",})
# 验证码
captcha = CaptchaField() def clean(self): # 验证码
try:
captcha_x = self.cleaned_data['captcha']
except Exception as e:
print 'except: '+ str(e)
raise forms.ValidationError(u"验证码有误,请重新输入") # 用户名
try:
username=self.cleaned_data['username']
except Exception as e:
print 'except: '+ str(e)
raise forms.ValidationError(u"注册账号需为邮箱格式") # 登录验证
is_email_exist = UserProfile.objects.filter(email=username).exists()
is_username_exist = UserProfile.objects.filter(username=username).exists()
if is_username_exist or is_email_exist:
raise forms.ValidationError(u"该账号已被注册") # 密码
try:
password=self.cleaned_data['password']
except Exception as e:
print 'except: '+ str(e)
raise forms.ValidationError(u"请输入至少8位密码"); return self.cleaned_data

 6.views.py

# 注册
# 改为ajax post
def register(request):
if request.method == 'POST':
# 验证码
print 'captcha_0: ' + request.POST.get('captcha_0')
print 'captcha_1: ' + request.POST.get('captcha_1')
try:
reg_form = RegisterForm(request.POST)
except Exception as e:
print str(e)
# 登录失败 返回错误提示
err = "注册失败,请重试"
return result_response(request, err) if reg_form.is_valid():
print "register success"
try:
username = reg_form.cleaned_data['username']
password = reg_form.cleaned_data['password']
user = UserProfile.objects.create(username = username, email = username,
password = make_password(password), is_active = True)
user.save()
#         # 指定默认的登录验证方式
user.backend = 'django.contrib.auth.backends.ModelBackend'
# 验证成功登录
auth.login(request, user)
return result_response(request, "")
except Exception as e:
print str(e)
setFormTips(reg_form, "注册失败,请重试")
else:
print "register failed" if request.POST.get('captcha_1') == "":
setFormTips(reg_form, "验证码不能为空") # 登录失败 返回错误提示
err = getFormTips(reg_form)
return result_response(request, err)
else:
reg_form = RegisterForm() return render(request, 'index.html', locals())

 7.html模板中显示验证码

第一种:
{{ reg_form.captcha }}
###这种方法对页面的适应性不太好,如上面模板变量生成html如下:
<input autocomplete="off" id="id_captcha_1" name="captcha_1" type="text">
<input id="id_captcha_0" name="captcha_0" type="hidden" value="e91228ab45df7338b59b64cb0eae1b60a48fd125">
<img src="/%2Fimage/e91228ab45df7338b59b64cb0eae1b60a48fd125/" alt="captcha" class="captcha"> 第二种:
#views.py
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url
hashkey = CaptchaStore.generate_key()
imgage_url = captcha_image_url(hashkey)
###这种方法给刷新验证码提供了方便,生成html如下:
<input type="text" id="id_reg_captcha_1" name="captcha_1" class="form-control form-control-captcha fl" placeholder="请输入验证码">
<span class="v5-yzm fr"><a href="#" class="next-captcha"><img src="{{ imgage_url }}" class="captcha" alt="captcha">换一张</a></span>
<input id="id_reg_captcha_0" name="captcha_0" type="hidden" value="{{ hashkey }}">

 8.刷新验证码

前台js

  // 刷新验证码
$(".next-captcha").click(function(){
$.getJSON("{% url 'refresh-captcha' %}", function(json) {
// This should update your captcha image src and captcha hidden input
// debugger;
var status = json['status'];
var new_cptch_key = json['new_cptch_key'];
var new_cptch_image = json['new_cptch_image'];
id_captcha_0 = $("#id_reg_captcha_0");
img = $(".captcha");
id_captcha_0.attr("value", new_cptch_key);
img.attr("src", new_cptch_image);
}); });

后台代码

# 刷新验证码
def refresh_captcha(request):
to_json_response = dict()
to_json_response['status'] = 1
to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
to_json_response['new_cptch_image'] = captcha_image_url(to_json_response['new_cptch_key'])
return HttpResponse(json.dumps(to_json_response), content_type='application/json')

django验证码配置与使用的更多相关文章

  1. Python Virtualenv运行Django环境配置

    系统: RHEL6.5 版本说明: Python-3.5.0 Django-1.10.4 virtualenv:为每个项目建立不同的/独立的Python环境,你将为每个项目安装所有需要的软件包到它们各 ...

  2. Django环境配置

    Django安装 #安装最新版本的Django $ pip install django #或者指定安装版本 pip install -v django==1.7.1 项目创建 $ django-ad ...

  3. 最优Django环境配置

    2 最优Django环境配置 本章描述了我们认为对于中等和高级Django使用者来说最优的本地环境配置 2.1 统一使用相同的数据库引擎 一个常见的开发者错误是在本地开发环境中使用SQLite3,而在 ...

  4. django框架配置mysql数据库

    django配置mysql数据库: 1.首先更改django项目文件中的settings.py的数据库配置 DATABASES = { 'default': { 'ENGINE': 'django.d ...

  5. ModelViewSet 路由 / django logging配置 / django-debug-toolbar使用

    一.ModelViewSet 路由 因为我们正在使用ViewSet代替View,实际上已经不再需要自己来设计URL的配置了.将资源和视图.URL绑定到一起是一个可以自动完成的过程,只需要使用Route ...

  6. Django media 配置

    Django  media 配置 settings.py 配置  配置 media 的路径, 以及连接到主路径 还要添加一个 上下文管理 TEMPLATES = [ { 'BACKEND': 'dja ...

  7. django-debug-toolbar和Django 日志配置

    django-debug-toolbar介绍 django-debug-toolbar 是一组可配置的面板,可显示有关当前请求/响应的各种调试信息,并在单击时显示有关面板内容的更多详细信息. gith ...

  8. django 验证码实现

    django验证码的使用: 验证码的作用:用于人机识别. 验证码 ###验证码: def code_str(request): from PIL import Image from PIL impor ...

  9. python 全栈开发,Day96(Django REST framework 视图,django logging配置,django-debug-toolbar使用指南)

    昨日内容回顾 1. Serializer(序列化) 1. ORM对应的query_set和ORM对象转换成JSON格式的数据 1. 在序列化类中定义自定义的字段:SerializerMethodFie ...

随机推荐

  1. 关于NuGet

    一.NuGet是什么? NuGet是Microsoft开发平台的程序集包管理器,它由客户端工具和服务端站点组成,客户端工具提供给用户管理和安装/卸载软件程序包,以及打包和发布程序包到NuGet服务端站 ...

  2. 2017ACM暑期多校联合训练 - Team 8 1008 HDU 6140 Hybrid Crystals (模拟)

    题目链接 Problem Description Kyber crystals, also called the living crystal or simply the kyber, and kno ...

  3. Mac 下安装 ruby 环境解决 brew 安装 yarn 问题

    在brew安装yarn提示 ruby的版本过低.在网上搜了一下发现 1. mac下自带的ruby 在 system 目录下 2. 其实可以用brew安装一个ruby brew install ruby ...

  4. struts获得参数(属性,对象,模型驱动)

    0. strutsMVC

  5. 大美西安writeup

    http://202.112.51.184:10080/ admin/admin 弱口令登入 发现注入 但是这个注入实在是不知道怎么利用.很蛋疼.后来get了一个姿势. 先-1让前面的不被下载然后后面 ...

  6. caffe Python API 之SoftmaxWithLoss

    net.loss = caffe.layers.SoftmaxWithLoss(net.fc3, net.label) 输出: layer { name: "loss" type: ...

  7. Firefox缓存文件夹位置设置及清除缓存方法

    地址栏敲入: about:config, 新建一个"browser.cache.disk.parent_directory", 并设置为你要的缓存文件夹, 例如:  "F ...

  8. geoip 扩展包根据ip定位详情

    教程:https://laravel-china.org/courses/laravel-package/2024/get-the-corresponding-geo-location-informa ...

  9. rds 与mysql 进行主从同步

    .rds上默认会有server-****,只需要配置从数据库: .从数据库的配置流程: .[mysqld] log-bin = mysql-bin-changelog #要和主库中的名字一样 rela ...

  10. JSP基础与提高(一).md

    JSP基础 JSP的由来 1.1. 为什么有JSP规范 Servlet技术产生以后,在使用过程中存在一个很大的问题,即为了表现页面的效果而需要输出大量的HTML标签,这些标签在Servlet中表现为一 ...