Django实现验证码

Django-simple-captcha模快

1.下载安装:

  window命令行输入:pip install django-simple-captcha  ;   pip install pillow

2.添加captcha:在setting中找到app再添加。

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
    'captcha',
]

# 执行命令进行数据迁徙,会发现数据库中多了一个 captcha_captchastore 的数据表 python manage.py migrate

 

3.添加路由:在urls.py中添加对应的路由。

from django.contrib import admin
from django.urls import path, include
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('captcha', include('captcha.urls')),
    path('home/', views.home)
]

 

4.添加form表单:在app目录下创建forms.py。

from django import forms
from captcha.fields import CaptchaField


class UserForm(forms.Form):
    username = forms.CharField(
        label='用户名',                # 在表单里表现为 label 标签
        max_length=128,
        widget=forms.TextInput(attrs={'class': 'form-control'})   # 添加 css 属性
    )

    captcha = CaptchaField(
        label='验证码',
        required=True,
        error_messages={
            'required': '验证码不能为空'
        }
    )

 5.视图函数:在view.py中完成home函数。

from django.shortcuts import render

# Create your views here.
from app01.forms import UserForm


def home(request):
    register_form = UserForm(request.POST)
    if register_form.is_valid():
        pass
    register_form = UserForm()
    return render(request, 'index.html', {'register_form': register_form})

 

 6.前端渲染:在templates目录下创建index.html。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="#" method="post">
    {{ register_form.captcha.label_tag }}
    {{ register_form.captcha }}
</form>

</body>
</html>

 

7. 运行结果:python manage.py runserver

Django实现验证码

 参考自:https://www.cnblogs.com/midworld/p/10992019.html

上一篇:Redis哨兵模式高可用解决方案


下一篇:sharepoint2010问卷调查(4)-实现问卷的重复答复次数(采用自定义字段类型和JS)