在编写一个关于验证码的程序时,lower()函数报错
vscode 运行代码
报错是:AttributeError: 'NoneType' object has no attribute 'lower'
还有提示的是 : if check_code and check_code.lower() == request.POST.get('captcha').lower():说这行报错,check_code 应该没有获取到值,但是在上一行代码中:check_code = request.session.get('code') 已经获取过了,不知道怎样修改代码
代码:
from io import BytesIO
from django.shortcuts import render,redirect
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from utils.captcha import generate_captcha
# Create your views here.
def login(request):
'''判断请求方式
如果是get请求, 返回登陆页面
如果是post请求, 进行登录校验
'''
if request.method == 'GET':
# 获取错误信息
error = request.session.get('error')
# 删除错误信息
request.session['error'] = ''
return render(request,'login.html',{'error':error})
else:
# 获取验证码
check_code = request.session.get('code')
# 如果验证码有值,并且和session中的验证码一致,则校验通过
if check_code and check_code.lower() == request.POST.get('captcha').lower():
# 获取用户名和密码
uname = request.POST.get('uname')
pwd = request.POST.get('pwd')
# 校验用户名和密码
user = auth.authenticate(username=uname,password=pwd)
# 判断用户是否存在
if user:
# 将用户信息保存到session中
auth.login(request,user)
# 跳转到首页
return redirect('index')
else:
# 将错误信息存储到session
request.session['error'] = '用户名或密码错误'
# 返回登录页面
return redirect('login')
else:
# 将错误信息存储到session
request.session['error'] = '验证码错误'
# 返回登录页面
return redirect('login')
def logout(request):
auth.logout(request)
return redirect('login')
@login_required(login_url='login') # 确保在直接访问index.时也必须要登陆,会跳转到login.html
def index(request):
return render(request,'index.html')
def captcha_img(request):
'''
返回验证码
'''
# 获取验证码图片和内容
img,code=generate_captcha()
# 将验证码内容保存到session中,用于校验
request.session['code'] = code
# 将图片返回给浏览器
# 创建一个流文件BytesIO
stream = BytesIO()
# 将图片保存到流文件中
img.save(stream,'png')
# 返回数据
return HttpResponse(stream.getvalue())
初学代码,望各位解答,谢谢
不知道你这个问题是否已经解决, 如果还没有解决的话: