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自动连接ssh的方法

本文实例讲述了Python自动连接ssh的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/python #-*- coding:utf-8 -*- import...

Python二维码生成识别实例详解

前言 在 JavaWeb 开发中,一般使用 Zxing 来生成和识别二维码,但是,Zxing 的识别有点差强人意,不少相对模糊的二维码识别率很低。不过就最新版本的测试来说,识别率有了现...

详解Python3中字符串中的数字提取方法

逛到一个有意思的博客在里面看到一篇关于ValueError: invalid literal for int() with base 10错误的解析,针对这个错误,博主已经给出解决办法,...

Python中isnumeric()方法的使用简介

 isnumeric()方法检查字符串是否仅由数字组成。这种方法只表示为Unicode对象。 注意:要定义一个字符串为Unicode,只需前缀分配'u'引号。以下是示例。 语法...

Python pass详细介绍及实例代码

Python pass的用法: 空语句 do nothing 保证格式完整 保证语义完整 以if语句为例,在c或c++/Java中: if(true) ; //do...