Django6 图形验证码

pip install -i https://pypi.mirrors.ustc.edu.cn/simple/ django-simple-captcha

settings

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'App',
    'captcha'  # 安装应用
]

# 图形验证码配置
# 证码设置
CAPTCHA_IMAGESIZE = (8,45)   # 设置captcha图片大小

CAPTCHA_LENGTH =4   #字符个数
CAPTCHA_TIMEOUT =1  #超时(minutes)*

# 输出格式:输入框验证码图片隐藏域•
# '%(image)s %(hidden_field)s %(text_field)s'
CAPTCHA_OUTPUT_FORMAT ='%(text_field)s %(image)s %(hidden_field)s'
CAPTCHA_NOISE_FUNCTIONS =(
    'captcha.helpers.noise_null',
    'captcha.helpers.noise_arcs',
    'captcha.helpers.noise_dots',
)
CAPTCHA_CHALLENGE_FUNCT =  'captcha.helpers.math_challenge'

urls

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include("App.urls")),
    path('captcha/',include("captcha.urls"))
]

App.urls

from django.urls import path
from App import views

app_name = "App"
urlpatterns = [
    path("cap/",views.handle_captcha, name='cap'),
]

App.views

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.

from App.forms import LoginForm


def handle_captcha(request):
    if request.method == "POST":
        form = LoginForm(request.POST,request)
        print(form)
        if form.is_valid():
            return HttpResponse("验证通过")
        else:
            return render(request, 'verifycode.html', locals())
    else:
        form = LoginForm()
        return render(request,'verifycode.html',locals())

App.forms

from django import forms
from captcha.fields import CaptchaField

class LoginForm(forms.Form):
    captcha = CaptchaField()  # 验证码字段

verifycode.html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<form action="{% url 'App:cap' %}" method="post">
    {% csrf_token %}
    {{ form.captcha }} {{ form.captcha.errors }} <br>
    <input type="submit">
form>
body>
html>
<script src="https://cdn.bootcss.com/jquery/1.12.3/jquery.min.js">script>
<script>
    //点击刷新验证码
    $(function () {
        $('.captcha').css({
            'cursor': 'pointer'
        });
        // ajax刷新
        $('.captcha').click(function () {
            console.log('click');
            $.get("{% url 'captcha-refresh' %}",
                function (result) {
                    $('.captcha').attr('src', result['image_url']);
                    $('#id_captcha_0').val(result['key'])
                });
        });
    })
script>

连接数据库,创建图形认证库

python manage.py makemigrations
python manage.py migrate

你可能感兴趣的:(5-web,django)