django captcha使用

安装:pip install django-simple-captcha

setting:

 

url配置(使用的django1.11.29的版本,2.0版本使用path):

然后同步数据库表:

python manage.py makemigrations

python manage.py migrate

定义验证码生产公共方法:

from captcha.helpers import captcha_image_url
from captcha.models import CaptchaStore


def create_captcha():
    to_json_response = dict()
    to_json_response['status'] = 1
    to_json_response['new_captcha_key'] = CaptchaStore.generate_key()
    to_json_response['new_captcha_image'] = captcha_image_url(to_json_response['new_captcha_key'])

    return to_json_response

form:

class ForgetPasswordForm(forms.Form):
    email=forms.CharField(required=True)
    captcha=CaptchaField(label='验证吗')

    def clean(self):
        clean_data=super().clean()
        captcha_data=clean_data.get('captcha')
        email=clean_data.get('email')
        user=User.objects.filter(Q(email=email)| Q(username=email))
        if not user:
            raise forms.ValidationError('邮箱不存在,重新输入')
        if captcha_data is None:
            raise forms.ValidationError('验证码有误请重新输入')
        return clean_data

html:

<div class="weui-cell weui-cell_vcode">
  <div class="weui-cell__hd"><label class="weui-label">验证码</label></div>
  <div class="weui-cell__bd">
    <input class="weui-input" type="text" name="captcha_1" placeholder="请输入验证码">
  </div>
  <div class="weui-cell__ft">
      <input type="hidden" name="captcha_0" value="{{ captcha.new_captcha_key }}">
      <img class="weui-vcode-img" id="login-vcode-img" src="{{ captcha.new_captcha_image }}">
  </div>
</div>

views:

def forget_password(request):
    if request.method=='POST':
        form=ForgetPasswordForm(request.POST)
        print(request.POST)
        if form.is_valid():
            request.session['email']=request.POST['email']
            return redirect('user:reset_password')
    else:
        form=ForgetPasswordForm()
    return render(request,'forget_password.html',{'captcha':create_captcha(),'form':form})
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值