【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

發佈了50 篇原創文章 · 獲贊 78 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章