File “F:\大四\毕业设计\设计\DSOnline\users\views.py”, line 18, in post
mobile=send_sms_form.cleaned_data[“mobile”]
TypeError: list indices must be integers or slices, not str
Views.py代码如图示
from django.shortcuts import render
from django.views.generic.base import View
from django.contrib.auth import authenticate,login,logout
from django.http import HttpResponseRedirect,JsonResponse
from django.urls import reverse #通过名称定为Url
from users.forms import LoginForm,DynamicLoginForm
from utils.YunPian import send_single_sms
from utils.random_str import generate_random
from DSOnline.settings import yp_apikey
#django内置的验证方法 login直接登录用户
# Create your views here.
class SendSmsView(View):
def post(self,request,*args,**kwargs):
send_sms_form=DynamicLoginForm(request.POST)
re_dict={}
if send_sms_form.is_valid():
mobile=send_sms_form.cleaned_data["mobile"]
#随机生成验证码
code=generate_random(6,0)
re_json=send_single_sms(yp_apikey,code,mobile=mobile) #发送短信验证码
if re_json["code"]==0:
re_dict["status"]=="success"
else:
re_dict["msg"]==re_json["msg"]
else:
for key,value in send_sms_form.errors.items():
re_dict[key]=value[0]
return JsonResponse({re_dict})
class LogoutView(View):
def get(self,request,*args,**kwargs):
logout(request)
return HttpResponseRedirect(reverse("index"))
class LoginView(View):
def get(self,request,*args,**kwargs):
if request.user.is_authenticated:
return HttpResponseRedirect(reverse("index")) #重定向到首页
login_form=DynamicLoginForm()
return render(request,"login.html",{"login_form":login_form})
def post(self,request,*args,**kwargs):
login_form=LoginForm(request.POST) #表单验证
if login_form.is_valid():
user_name=login_form.cleaned_data["username"]
password=login_form.cleaned_data["password"]
#通过用户和密码查询用户是否存在
user=authenticate(username=user_name,password=password)
if user is not None:
login(request,user)#查询到用户
#登录成功之后 跳转到什么页面——首页
return HttpResponseRedirect(reverse("index"))
else:
return render(request, "login.html", {"msg":"用户名或密码错误","login_form":login_form})
else:
return render(request, "login.html", {"login_form":login_form})
forms.py代码
from django import forms
from captcha.fields import CaptchaField
class LoginForm(forms.Form):
username=forms.CharField(required=True,min_length=2) #与前端html input名字保持一致
password=forms.CharField(required=True,min_length=3)
class DynamicLoginForm(forms.Form):
captcha = CaptchaField()
mobile = forms.CharField(required=True,min_length=11,max_length=11)