【Django】Django验证码插件Django-simple-captcha自定义样式,以及通过ajax发送验证码数据

一、简单安装配置

1、安装django-simple-captcha

pip install django-simple-captcha

2、将captcha 添加到setting.py文件中的installed_apps里面

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'captcha',
]

3、将captcha配置在url.py文件中

from django.conf.urls import url,include
urlpatterns = [
    ……
    url(r'^captcha/', include('captcha.urls')), 
]

4、迁移同步,生成captcha所依赖的表

python manage.py migrate

二、使用

1、将captcha字段在form类中进行设置

from captcha.fields import CaptchaField
class UserRegisterForm(forms.Form):
	……
   captcha = CaptchaField()

2、在后台逻辑当中,get请求里面实例化我们的form,将form对象返回到页面

def user_register(request):
	if request.method == 'GET':
		user_register_form = UserRegisterForm()
		return render(request,'register.html',{'user_register_form':user_register_form})

3、在页面上通过{{ form.captcha}} 获取验证码

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <form action="">
        {{ form_obj.captcha}}
    </form> 
</body>
</html>

效果如下图所示

如果想要修改布局,可以自己定义css样式改,也可以在配置中进行修改。

三、修改布局属性

官方文档:https://django-simple-captcha.readthedocs.io/en/latest/usage.html

1、修改布局(调整输入框和图片的位置)

我们只需要在setting.py文件中添加CAPTCHA_OUTPUT_FORMAT属性

text_field是文本框,image时图片,这个hidden_field是隐藏属性,随便放哪个位置不影响,保存的是这个验证码的id。

2、修改input的属性

官方文档写到,我们可以重新写一个模板,将该模板的路径赋予给CAPTCHA_FIELD_TEMPLATE这个属性,这个属性也和上面添加的CAPTCHA_OUTPUT_FORMAT属性一样定义在settings.py中。 所以我们可以写一个模板,然后赋予属性就可以了。

这边我们将模板定义在了templates/captcha路径下。

<!--text_field.html-->
<input class='user_input' id="id_captcha_1" name="captcha_1" placeholder='验证码' placeholder-data="验证码" />

3、修改样式

用id选择器选择验证码输入框默认的id"#id_captcha_1",用类选择器选择验证码图片默认的class".captcha"。然后自己去改样式吧。

四、用ajax传包含验证码的表单数据

js

var login_data = { "email" :$("#email").val(), "password":("#password").val(),  "captcha_0": $("#id_captcha_0").val(), "captcha_1": $("#id_captcha_1").val()};  

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    headers: { "X-CSRFToken": {{ csrf_token }} },
    url: "/login/",
    dataType: "json",
    cache: false,
    data: JSON.stringify(login_data),
    error: function () {
        ShowErrorMessage("登录失败!");
    },
    success: function (data) {
        if (null != data && "" != data) {
            alert(data);
        }
    }
});

view

def post(self, request):

    data = json.loads(request.body)
    login_form = LoginForm(data)

    if login_form.is_valid():
        email_account = data["email"]
        pass_word =data["password"]

五、用Ajax刷新验证码

//点击验证码刷新
$(function() {
    $('.captcha').css({
        'cursor': 'pointer'
    })
    // ajax 刷新
    $('.captcha').click(function () {
        console.log('click');
        $.getJSON("/captcha/refresh/",
            function (result) {
                $('.captcha').attr('src', result['image_url']);
                $('#id_captcha_0').val(result['key']);
            }
        );
    });
});

参考:

1、http://django-simple-captcha.readthedocs.io/en/latest/usage.html#installation

2、https://blog.csdn.net/weixin_41227756/article/details/102580816

3、https://blog.csdn.net/tanzuozhev/article/details/50458688

猜你喜欢

转载自blog.csdn.net/BobYuan888/article/details/104044470