文章目录

在网站开发的登录页面中,经常会需要使用到图形验证码来验证。在Django中,django-simple-captcha库包提供了图形验证码的使用。
Django-captcha是一个图形验证码第三方插件,官网地址:https://django-simple-captcha.readthedocs.io/en/latest/usage.html.。其用法主要有以下3步:
1.安装django-simple-captcha库
pip install django-simple-captcha
# 如果安装有依赖库问题,请执行下面的安装
apt-get -y install libz-dev libjpeg-dev libfreetype6-dev python-dev
2.设置
在settings中安装captcha应用
设置captcha的基本样式
captcha的输出样式由字符串:%(text_field)s %(image)s %(hidden_field)s,其中:
%(text_field)s表示用户输入验证码的输入框
%(image)s验证码图片
%(hidden_field)s隐藏域
captcha有三种基本验证码样式:
1.随机字符
CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.random_char_challenge’
2.简单数学计算
CAPTCHA_CHALLENGE_FUNCT = ‘captcha.helpers.math_challenge’
3.单词
CAPTCHA_CHALLENGE_FUNCT = ‘captcha.helpers.word_challenge’
在根路由中添加captcha的路由
最后要迁移数据库:
python manage.py migrate
之所以要迁移数据库是因为captcha不使用cookie和session保存验证码,而是由数据库保存,所以captcha需要迁移数据库生成表:
其中:
challenge存储是验证码字符串(表达式)、单词等,
response存储数学表达式的值,小写的验证码字符串;
hashkey是唯一标示
expiration过期时间
建立表单
比如说,一般情况下我们会在登录中使用图形验证码,使用captcha最简单的方法是用表单。
# forms.py
from django import forms
from captcha.fields import CaptchaField
class LoginForm(forms.Form):
username = forms.CharField(max_length=20,min_length=3)
password = forms.CharField(max_length=128,widget=forms.PasswordInput())
captcha = CaptchaField() # 验证码字段
用表单实现
应用路由设置:
urlpatterns = [
.....
path('login/',views.user_login,name='login'),
]
视图函数:
import json
from django.contrib.auth import authenticate
import django.contrib.auth as auth
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
def user_login(request):
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get