Django使用django-simple-captcha模块实
Django前端页面验证码功能的实现,使用最广的是django-simple-captcha模块,该模块入门简单,只需要如下几步就可开始使用
基础环境:CentOS7.2、python3.5、Django2.07
1、安装Pillow和django-simple-captcha : pip install Pillow , pip install django-simple-captcha
2、在project的settings.py中注册captcha
INSTALLED_APPS = [
.....
'captcha',
.....
]
3、运行 python3 manager.py migrations 和 python3 manage.py migrate,生成captcha需要的数据库表。
其中captcha_captchastore这张表保存的是图形验证码内容
4、配置URL路由,在url.py文件中加入如下这行:
urlpatterns = [
.....
path('captcha', include('captcha.urls')),
.....
]
5、在forms.py表单加入验证码模块(CaptchaField),例如:
from django import forms
from captcha.fields import CaptchaField
class UserForm(forms.Form):
username = forms.CharField(label="用户名", max_length=128, widget=forms.TextInput(attrs={'class': 'form-control'}))
password = forms.CharField(label="密码", max_length=256, widget=forms.PasswordInput(attrs={'class': 'form-control'}))
captcha = CaptchaField(label='验证码')
6、views.py文件代码如下:
from django.shortcuts import render,redirect
from . import forms
from . import models
.....
def login(request):
if request.method == "POST":
login_form = forms.UserForm(request.POST)
message = "请检查填写的内容!"
if login_form.is_valid():
username = login_form.cleaned_data['username']
password = login_form.cleaned_data['password']
try:
user = models.User.objects.get(name=username)
if user.password == password:
return redirect('/index/') ####redirect中的URL前面不加'/',返回的URL是当前URL+redirect中的URL;要使返回的URL是redirect中的URL,redirect中的URL前面加'/'。
else:
message = "密码不正确!"
except:
message = "用户名不存在!"
return render(request, 'login.html', locals())
login_form = forms.UserForm()
return render(request, 'login.html', locals())
.....
7、前端页面base.html和login.html
base.html
{% load staticfiles %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>{% block title %}base{% endblock %}</title>
<!-- Bootstrap -->
<link href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
{% block css %}{% endblock %}
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#my-nav" aria-expanded="false">
<span class="sr-only">切换导航条</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Mysite</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="my-nav">
<ul class="nav navbar-nav">
<li class="active"><a href="/logintest/index/">主页</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="/logintest/login/">登录</a></li>
<li><a href="/logintest/register/">注册</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
{% block content %}{% endblock %}
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="{% static 'js/jquery-3.3.1.min.js' %}"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
{% block script %}{% endblock %}
</body>
</html>
login.html
{% extends 'login/base.html' %}
{% load staticfiles %}
{% block title %}登录{% endblock %}
{% block css %}
<link href="{% static 'bootstrap-3.3.7-dist/css/login.css' %}" rel="stylesheet"/>
{% endblock %}
{% block content %}
<div class="container">
<div class="col-md-4 col-md-offset-4">
<form class='form-login' action="/logintest/login/" method="post">
{% if message %}
<div class="alert alert-warning">{{ message }}</div>
{% endif %}
{% csrf_token %}
<h2 class="text-center">欢迎登录</h2>
<div class="form-group">
{{ login_form.username.label_tag }}
{{ login_form.username}}
</div>
<div class="form-group">
{{ login_form.password.label_tag }}
{{ login_form.password }}
</div>
<div class="form-group">
{{ login_form.captcha.errors }}
{{ login_form.captcha.label_tag }}
{{ login_form.captcha }}
</div>
<button type="reset" class="btn btn-default pull-left">重置</button>
<button type="submit" class="btn btn-primary pull-right">提交</button>
</form>
</div>
</div> <!-- /container -->
{% endblock %}
8、更新文件重启Django server
9、动态更新验证码
前面的示例都很简单,复制黏贴就可以直接使用。
但是验证码部分有一个问题,如果看不清当前的验证码,想要换一个,需要刷新整个页面。一刷新,前面输入的账号密码信息就都没有了,这并不是一个友好的处理方式。
所以我们还需要对他进行优化,让他能只更新验证码图片,而不动我们已经填好的账号密码信息。
优化使用ajax方式来实现,在前面的login.html文件最下方中增加如下一段内容,便可实现点击验证码图片更新验证码信息功能。
{% block script %}
<script>
$(function () {
$('.captcha').css({
'cursor': 'pointer'
});
$('.captcha').click(function () {
$.getJSON("/captcha/refresh/",
function (result) {
$('.captcha').attr('src', result['image_url']);
$('#id_captcha_0').val(result['key'])
});
});
})
</script>
{% endblock %}