快速實現Django admin登陸增長驗證碼驗證功能

首先,須要安裝一個驗證碼的第三方庫-django-simple-captcha,這是一個極其簡單但可高度定製的 Django 第三方應用程序,用於將驗證碼圖像添加到任何 Django 表單。html

_images/captcha3.png

安裝

  1. 經過pip安裝django-simple-captcha
 pip install django-simple-captcha
複製代碼
  1. 添加captchasettings.pyINSTALLED_APPS
 INSTALLED_APPS = [
     ...
     'captcha'
 ]
複製代碼
  1. 生成數據,命令行運行python manage.py migrate
  2. 添加url到項目的urls.py文件中
 urlpatterns = [
     path('captcha/', include('captcha.urls')),
 ]
複製代碼

建立一個dadmin的APP

  1. 建立一個dadmin的APP,並將其添加到settings.pyINSTALLED_APPS
 python manage.py startapp dadmin
複製代碼

1.JPG

  1. 在dadmin中建立一個forms.py的文件,咱們繼承django自帶的登陸表單AuthenticationForm,並對其進行擴展!
 # dadmin/forms.py
 
 from django.contrib.auth.forms import AuthenticationForm
 from captcha.fields import CaptchaField

 class DadminAuthenticationForm(AuthenticationForm):
     captcha = CaptchaField()
複製代碼

2.JPG

  1. 在dadmin的同級建立一個templates的文件夾,並在其內部建立一個dadmin的文件夾,將django默認的登陸模板中的代碼所有拷貝過來,並在密碼框下添加驗證碼的輸入框!
 <div class="form-row">
     {{ form.captcha.errors }}
     {{ form.captcha.label_tag }} {{ form.captcha }}
     <input type="hidden" name="next" value="{{ next }}">
   </div>
複製代碼

3.JPG 4. 在dadmin中的admin.py中添加以下代碼,這裏咱們子類化了AdminSite類,這樣咱們就能夠隨意修改和覆蓋django 默認admin的任何模板,而且不會影響默認admin的任何東西,還能夠繼承admin的全部功能及模板!python

 from django.contrib import admin

 # Register your models here.
 from .forms import DadminAuthenticationForm

 class DadminSite(admin.AdminSite):
     login_form = DadminAuthenticationForm
     login_template = "dadmin/login.html"

 admin_site = DadminSite(name='dadmin')

複製代碼
  1. 在項目的urls.py中註冊剛纔子類化的站點地址
 from dadmin.admin import admin_site

 urlpatterns = [
     path('admin/', admin.site.urls),
     path('myadmin/', admin_site.urls),
     path('captcha/', include('captcha.urls')),
 ]
複製代碼

4.JPG

  1. 終端啓動站點
python3 manage.py runserver
複製代碼

5.JPG

瀏覽器打開站點能夠看到驗證碼已經添加成功了,但彷佛樣式不美觀,這個就留給你們本身去研究吧,給個思路,能夠拷貝captcha默認的驗證碼模板,樣式重寫便可!jquery

  1. 實現點擊更換驗證碼功能

將以下代碼加入到login.html模板的底部便可,別忘了引入Jquery.js哦!ajax

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>django

<script>
    $('img.captcha').attr("title", "點擊更換驗證碼");
    $('img.captcha').click(function() {
        $.getJSON('/captcha/refresh/',function(json) {
            // This should update your captcha image src and captcha hidden input
            console.log(json);
            $("img.captcha").attr("src",json.image_url);
            $("#id_captcha_0").val(json.key);
        });
        return false;
    });
  </script>
複製代碼

到此大功告成,很簡單的驗證碼功能就完成了!json

若是你也在自學Python或Django,那就請關注我吧,會不斷輸送關於django及python的技術乾貨,以及小案例!後端

下篇預告:django實現先後端分離登陸功能,並加入驗證碼功能!瀏覽器

相關文章
相關標籤/搜索