django-simple-captcha 验证码插件使用

2018-09-03  本文已影响0人  程心vs艾AA

安装部署

版本:django 1.9

1pip install django-simple-captcha==0.4.6

settings.py配置,加入captcha

INSTALLED_APPS = [

'captcha',

]

urls.py配置

加入url
from django.urls import path,include
path('captcha', include('captcha.urls')),

数据库同步

makemigrations

migrate

form定义

app下自定义froms.py文件,创建一个注册form

from django import forms

from captcha.fields import CaptchaField

class RegisterForm(forms.Form):

email = forms.EmailField(required=True)

password = forms.CharField(required=True, min_length=5)

captcha = CaptchaField(error_messages={"invalid": u"验证码错误"})

views.py代码
from django.views.generic.base import View

    def get(self, request):
        # 实例化表单对象,里面包含验证码
        register_forms = RegisterForms()
        #返回表单
        return render(request, 'register.html',{'register_forms':register_forms})

    def post(self, request):
        #表单验证
        register_forms = RegisterForms(request.POST)
        if register_forms.is_valid():
            # 验证成功存储账号密码
            email = request.POST.get('email')
            password = request.POST.get('email')
            #实例化对象存入数据
            user_pro = UserProfile()
            user_pro.email = email
            user_pro.password = password
            #写入数据库
            user_pro.save()
            return render(request,'register.html',{'msg':'注册成功'})
        else:

            return render(request, 'register.html', {'register_forms': register_forms})
    

html页面引用
验证码
<div class="form-group marb8 captcha1 ">
                            <label>验&nbsp;证&nbsp;码</label>
                            {{ register_forms.captcha }}
错误信息
 <div class="error btns" id="jsEmailTips">
                         {{ msg }}
                              {% for key , value in register_forms.errors.items%}
                           {{ value }}
                        {% endfor %}
上一篇下一篇

猜你喜欢

热点阅读