首先,须要安装一个验证码的第三方库-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实现先后端分离登陆功能,并加入验证码功能!浏览器