Django为窗体加上防机器人的验证码功能过程解析

yipeiwu_com6年前Python基础

这里我们使用 django-simple-captcha 模块,官方介绍如下:https://github.com/mbi/django-simple-captcha

一键安装:

pip install django-simple-captcha

在 setting.py 中把 'captcha' 加到 INSTALLED_APP 的区块中

INSTALLED_APPS = (
  # ...
  'captcha',
  # ... 
)

由于此模块会到数据库建立自己的数据表,因此要先执行数据库的 migrate 操作:

python manage.py migrate

在 urls.py 中加上这个模块对应的网址:

from django.urls import path, re_path, include
urlpatterns = [
  #...
  url(r'^captcha/', include('captcha.urls'),
  # ...
]

在窗体类中加上 CaptchaField 字段 :

from captcha.fields import CaptchaField
class PostForm(forms.ModelForm):
  captcha = CaptchaField() #CaptchaField 字段
  class Meta:
    model = models.Post
    fields = ['mood', 'nickname', 'message', 'del_pass']

  def __init__(self, *args, **kwargs):
    super(PostForm, self).__init__(*args, **kwargs)
    self.fields['mood'].label = '现在的心情'
    self.fields['nickname'].label = '您的昵称'
    self.fields['message'].label = '心情留言'
    self.fields['del_pass'].label = '设置密码'
    self.fields['captcha'].label = '请输入验证码'

运行结果如下:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python写的Tkinter程序屏幕居中方法

本文适用场景:想用Tkinter开发界面程序并屏幕居中,但没找到相应的API。 这两天玩了玩Tkinter,感觉不错,就是屏幕居中这个问题在网上搜了很长时间也没 找到答案,最后没办法,...

解决Python出现_warn_unsafe_extraction问题的方法

解决Python出现_warn_unsafe_extraction问题的方法

在Python项目中运行出现了“AttributeError: ResourceManager instance has no attribute ‘_warn_unsafe_extra...

springboot配置文件抽离 git管理统 配置中心详解

springboot配置文件抽离,便于服务器读取对应配置文件,避免项目频繁更改配置文件,影响项目的调试与发布 1.创建统一配置中心项目conifg 1)pom配置依赖 <pa...

浅谈Python_Openpyxl使用(最全总结)

Python_Openpyxl 1. 安装 pip install openpyxl 2. 打开文件 ① 创建 from openpyxl import Workboo...

python与sqlite3实现解密chrome cookie实例代码

本文研究的主要问题:有一个解密chrome cookie的事情,google出了代码,却不能正常执行,原因在于sqlite3的版本太低,虽然我切换到了python3.5的环境,但sqli...