django验证码界面和视图函数 setting

settings.py

CAPTCHA_OUTPUT_FORMAT = '%(text_field)s %(hidden_field)s %(image)s'

CAPTCHA_NOISE_FUNCTIONS = (
    # 设置样式
    'captcha.helpers.noise_null',
    # 设置干扰线
    'captcha.helpers.noise_arcs',
    # 设置干扰点
    'captcha.helpers.noise_dots',
)

# 图片大小
CAPTCHA_IMAGE_SIZE = (100, 25)
# 设置图片背景色
CAPTCHA_BACKGROUND_COLOR = '#ffffff'
# 图片中的文字为随机数字表达式
CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.math_challenge'
# 设置字符的个数
CAPTCHA_LENGTH = 4
# 设置超时
CAPTCHA_TIMEOUT = 1

views.py

from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import login, authenticate
from .forms import CaptchaTestForm
from django.http import JsonResponse
from captcha.models import CaptchaStore
# Create your views here.

def loginView(request):
    if request.method == 'POST':
        form = CaptchaTestForm(request.POST)
        if form.is_valid():
            u = form.cleaned_data['username']
            p = form.cleaned_data['password']
            if User.objects.filter(username=u):
                user = authenticate(username=u, password=p)
                if user:
                    if user.is_active:
                        login(request, user)
                        tips = '登录成功'
                else:
                    tips = '用户名或密码错误'
            else:
                tips = '用户不存在,请注册'
    else:
        form = CaptchaTestForm()
    return render(request, 'user.html', locals())



def ajax_val(request):
    if request.is_ajax():
        r = request.GET['response']
        h = request.GET['hashkey']
        cs = CaptchaStore.objects.filter(response=r, hashkey=h)
        if cs:
            json_data = {'status': 1}
        else:
            json_data = {'status': 0}
        return JsonResponse(json_data)
    else:
        json_data = {'status': 0}
        return JsonResponse(json_data)

user.htm

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/mobi.css/dist/mobi.min.css">
</head>
<body>
<div class="flex-center">
    <div class="container">
        <div class="flex-center">
            <div class="unit-1-2 unit-1-on-mobile">
                <h1>Mydjango Verification</h1>
                {% if tips %}
                    <div>{{ tips }}</div>
                {% endif %}
                <form action="" class="form" method="post">
                    {% csrf_token %}
                    <div>用户名:{{ form.username }}</div>
                    <div>密码:{{ form.password }}</div>
                    <div>验证码:{{ form.captcha }}</div>
                    <button type="submit" class="btn btn-primary btn-block">确定</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    $('.captcha').click(function () {
        console.log('click');
        $.getJSON("/captcha/refresh/", function (result) {
            $('.captcha').attr('src', result['image_url']);
            $('#id_captcha_0').val(result['key'])
        });
    });

    $('#id_captcha_1').blur(function () {
        json_data = {
            'response': $('#id_captcha_1').val(),
            'hashkey': $('#id_captcha_0').val()
        }
        $.getJSON('/ajax_val', json_data, function (data) {
            $('#captcha_status').remove()
            if (data['status']) {
                $('#id_captcha_1').after('<span id="captcha_status">验证码正确</span>')
            } else {
                $('#id_captcha_1').after('<span id="captcha_status">验证码错误</span>')
            }
        })
    })
</script>
</body>
</html>

forms.py

from django import forms
from captcha.fields import CaptchaField

class CaptchaTestForm(forms.Form):
    username = forms.CharField(label='用户名')
    password = forms.CharField(label='密码', widget=forms.PasswordInput)
    captcha = CaptchaField()

 

posted @ 2020-02-21 17:40  jackpod  阅读(184)  评论(0编辑  收藏  举报