2025年3月22日 星期六 甲辰(龙)年 月廿一 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

Django实现刷新验证码功能

时间:02-21来源:作者:点击数:32

很多场景需要验证码功能,比如登录。我们可以直接使用django的第三方库 django-simple-captcha 模块来实现验证码功能,但是如果需要刷新验证码,还需要做一些操作才行。我们还是可以使用django的第三方库 django-simple-captcha 模块来实现验证码刷新功能。

安装该模块

  • pip install django-simple-captcha

captcha模块结合form表单使用方法如下:

forms.py文件:

  • #forms.py
  • from django import forms
  • from captcha.fields import CaptchaField
  • class UserForm(forms.Form):
  • username = forms.CharField(label="用户名", max_length=128, widget=forms.TextInput(
  • attrs={'class': 'form-control', 'placeholder': "Username", 'autofocus': ''}))
  • password = forms.CharField(label="密码", max_length=256,
  • widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': "Password"}))
  • captcha = CaptchaField(label='验证码') #这个是验证码标签

urls.py文件:

  • #urls.py
  • from django.urls import include
  • from captcha.views import captcha_refresh # 验证码刷新功能,captcha_refresh为captcha.views内置方法,不需要我们单独写
  • urlpatterns = [
  • path('admin/', admin.site.urls),
  • path('login/', views.login),
  • path('captcha/', include('captcha.urls')), # 生成验证码
  • path('refresh/', captcha_refresh), # 点击可以刷新验证码
  • ]

captcha.views 内置就有刷新验证码的方法,因此我们不必再自己去写了,非常方便。

模版文件(login.html):

  • <!-- login.html -->
  • {#刷新验证码的脚本,放到body部分的最后面即可#}
  • <script>
  • $('.captcha').click(function () {
  • $.getJSON('/captcha/refresh/',function (result) {
  • $('.captcha').attr('src',result['image_url']);
  • $('#id_captcha_0').val(result['key']);
  • });
  • });
  • </script>

只需要修改上述几个文件的代码,其它地方均不需要改动,验证码即可点击进行刷新。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门