django 验证码如何使用?

发表时间:2019-10-23 10:54:26
摘要信息

django 验证码怎么使用

新建form.py

from django import forms
from captcha.fields import CaptchaField


# 管理后端登陆表单生成
class LoginForm(forms.Form):
user = forms.CharField(min_length=4, max_length=16, error_messages={
"required": "账号不能为空",
'min_length': '账号不能少于4位',
'max_length': '账号不能超过16位',
}, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'user', 'placeholder': '请输入账号'}))
password = forms.CharField(min_length=4, max_length=16, error_messages={
"required": "密码不能为空",
'max_length': '密码不能超过16位',
'min_length': '账号不能少于6位'
}, widget=forms.PasswordInput(attrs={'class': 'form-control', 'name': 'password', 'placeholder': '请输入密码'}))
captcha = CaptchaField(label='验证码')

然后在控制器中引入

from admin.form import *

视图控制器

loginForm = LoginForm()

生成登陆表单,并渲染到模板

if request.admin != None:
return HttpResponseRedirect('/admin')
template = loader.get_template('admin/login.html')
context = {
'form': loginForm
}
return HttpResponse(template.render(context, request))
<form action="#">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
{{ field }}
</div>
{% endfor %}
<button class="btn btn-lg btn-primary btn-block" onclick="formSubmit(this)">登录</button>
</form>

点击图片切换验证码

$('.captcha').click(function () {
$.getJSON("/refresh_captcha/", function (result) {
$('img.captcha').attr('src', result['image_url']);
$('#id_captcha_0').val(result['hashkey'])
});
});
});

urls.py添加两个路由

path('captcha/', include('captcha.urls')),  # 验证码
path('refresh_captcha/', admin_views.refresh_captcha), # 验证码刷新


post验证

if jarge_captcha(requestJson.get('code'), requestJson.get('captcha_0')):
try:
admin = p_admin.objects.get(user=requestJson.get('user'))
if admin.password == requestJson.get('password'):
request.session['admin'] = requestJson.get('user')
data = {
'status': 200,
'msg': '登陆成功',
'data': None
}
return HttpResponse(json.dumps(data, ensure_ascii=False),
content_type="application/json,charset=utf-8")
else:
data = {
'status': 200,
'msg': '账号或者密码错误',
'data': None
}
return HttpResponse(json.dumps(data, ensure_ascii=False),
content_type="application/json,charset=utf-8")
except:
data = {
'status': 200,
'msg': '账号或者密码错误',
'data': None
}
return HttpResponse(json.dumps(data, ensure_ascii=False), content_type="application/json,charset=utf-8")
else:
data = {
'status': 400,
'msg': '验证码错误',
'data': None
}
return HttpResponse(json.dumps(data, ensure_ascii=False), content_type="application/json,charset=utf-8")



40% Complete (success)