要实现django图形验证码,可以使用简单的captcha
一、安装captcha
在Pycharm的terminal中,使用pip安装第三方库:
执行命令:
pip install django-simple-captcha
二、注册captcha
在settings中,将‘captcha’注册到app列表里:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'login',
'captcha',
]
三、captcha需要在数据库中建立自己的数据表,所以需要执行migrate命令生成数据表:
migrate
四、添加路由,在urls.py中增加这一行
path('captcha/', include('captcha.urls'))
五、表单中添加对应代码。
from captcha.fields import CaptchaField #添加这里
class UserForm(forms.Form):
username =forms.CharField(label='用户名',max_length=128,widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': "Username",'autofocus': ''}))
password = forms.CharField(label='密码',max_length=256,widget=forms.PasswordInput(attrs={'class': 'form-control','placeholder': "Password"}))
captcha = CaptchaField(label="验证码") #添加这里
六、登录目标login.html中代码
{% load static %}
登录{% if myform.captcha.errors %}
{% elif message %}
{% endif %}
{% csrf_token %}
欢迎登录!
{{ myform.username.label_tag }}
{{ myform.username }}
{{ myform.password.label_tag }}
{{ myform.password }}
{{ myform.captcha.label_tag}}
{{ myform.captcha}}
新用户注册:
登录
{# 以下三者的引用顺序是固定的#}
其中图形验证码关键代码为:
{{ myform.captcha.label_tag}}
{{ myform.captcha}}