美文网首页
Django验证码

Django验证码

作者: Ancestor楠 | 来源:发表于2020-03-26 13:16 被阅读0次

验证码

验证码主要的作用是为了验证作用,现在验证码也有很多类型,比如滑动、点击、倒立点击特别多,这些都是为了加强网站的安全。

安装:

pip install django-simple-captcha

配置:

INSTALLED_APPS = [

'captcha',

]

路由:

path('captcha/', include('captcha.urls')),

创建表单

在应用下创建forms.py文件,内容为

from django import forms

from django.core.exceptions import ValidationError

from captcha.fields import CaptchaField         #按得拓展属性

from django.forms import widgets

import re

def mobile_validate(value):

    mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')

    if not mobile_re.match(value):

        raise ValidationError('手机号码格式错误')

class ContactForm(forms.Form):

    name = forms.CharField(required=True, error_messages={'required': '姓名不能为空.'},

                          widget=widgets.Input(attrs={"class": 'contactFormText', 'placeholder': '请填写姓名'}))

    phone = forms.CharField(validators=[mobile_validate],

                            widget=widgets.TextInput(attrs={"class": 'contactFormText', 'placeholder': '请填写手机号码'}))

    captcha = CaptchaField(required=True, error_messages={'invalid': '验证码错误'})

迁移文件

python manage.py migrate

模板 视图

刷新验证码

类选择器.captcha,

点击click,

回调函数function,

发起请求getJSON 

 请求地址/captcha/refresh/

<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>

<script>

    $('.captcha').click(function () {

        $.getJSON("/captcha/refresh/", function (result) {

            $('.captcha').attr('src', result['image_url']);

            $('#id_captcha_0').val(result['key'])

        });

    });

</script>

相关文章

网友评论

      本文标题:Django验证码

      本文链接:https://www.haomeiwen.com/subject/mctcuhtx.html