验证码的开发(插件方式)
一、使用验证码插件(推荐使用)
二、使用验证码的步骤
1、安装包
pipenv install django-simple-captcha
2、在
settings.py
中注册app
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'xadmin', 'crispy_forms', 'captcha', # 新增验证码app 'users', 'course', 'operation', 'organization' ]
3、运行命令生成数据库
python manage.py makemigrations python manage.py migrate
4、配置总的
url
from django.urls import path, include import xadmin from users.views import index urlpatterns = [ path('xadmin/', xadmin.site.urls), path('', index.IndexView.as_view(), name='home'), ... path('captcha/', include('captcha.urls')) ]
5、创建
forms.py
表单from django import forms from captcha.fields import CaptchaField class RegisterForm(forms.Form): """ 用户注册的form """ email = forms.EmailField(required=True, error_messages={'required': '用户名不能为空'}) password = forms.CharField(required=True, min_length=5, error_messages={'required': '密码不能为空', 'min_length': '密码长度太短'}) # 验证码的字段 captcha = CaptchaField()
6、在视图中使用
forms.py
表单class RegisterView(View): def get(self, request, *args, **kwargs): register_form = RegisterForm() # 把数据返回给前端 return render(request, 'register.html', {'register_form': register_form})
7、前端展示图片验证码
... <div class="form-group marb8 captcha1 "> <label>验 证 码</label> # 注意这个地方的金甲2的模板语法不能解析 " register_form.captcha " </div> ...
8、补充说明(前端点击验证码刷新验证码)
//刷新验证码 function refresh_captcha(event){ $.get("/captcha/refresh/?"+Math.random(), function(result){ $('#'+event.data.form_id+' .captcha').attr("src",result.image_url); $('#id_captcha_0').attr("value",result.key); }); return false; }