首先,須要安裝一個驗證碼的第三方庫-django-simple-captcha
,這是一個極其簡單但可高度定製的 Django 第三方應用程序,用於將驗證碼圖像添加到任何 Django 表單。html
django-simple-captcha
pip install django-simple-captcha
複製代碼
captcha
到settings.py
的INSTALLED_APPS
中 INSTALLED_APPS = [
...
'captcha'
]
複製代碼
python manage.py migrate
urls.py
文件中 urlpatterns = [
path('captcha/', include('captcha.urls')),
]
複製代碼
settings.py
的INSTALLED_APPS
中 python manage.py startapp dadmin
複製代碼
AuthenticationForm
,並對其進行擴展! # dadmin/forms.py
from django.contrib.auth.forms import AuthenticationForm
from captcha.fields import CaptchaField
class DadminAuthenticationForm(AuthenticationForm):
captcha = CaptchaField()
複製代碼
<div class="form-row">
{{ form.captcha.errors }}
{{ form.captcha.label_tag }} {{ form.captcha }}
<input type="hidden" name="next" value="{{ next }}">
</div>
複製代碼
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')
複製代碼
from dadmin.admin import admin_site
urlpatterns = [
path('admin/', admin.site.urls),
path('myadmin/', admin_site.urls),
path('captcha/', include('captcha.urls')),
]
複製代碼
python3 manage.py runserver
複製代碼
瀏覽器打開站點能夠看到驗證碼已經添加成功了,但彷佛樣式不美觀,這個就留給你們本身去研究吧,給個思路,能夠拷貝captcha默認的驗證碼模板,樣式重寫便可!jquery
將以下代碼加入到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實現先後端分離登陸功能,並加入驗證碼功能!瀏覽器