Python localhost和Heroku主机中的多值DictKeyError各不相同
我目前正在学习django,并创建了一个简单的TODO项目,该项目具有otp身份验证功能。在localserver中运行项目时,otp生成并存储在模型中,然后使用Python localhost和Heroku主机中的多值DictKeyError各不相同,python,django,postgresql,heroku,deployment,Python,Django,Postgresql,Heroku,Deployment,我目前正在学习django,并创建了一个简单的TODO项目,该项目具有otp身份验证功能。在localserver中运行项目时,otp生成并存储在模型中,然后使用if(t.otp==int(request.POST['otp']):匹配该模型,其中t是一个模型对象。这个很好用。为了测试,我在heroku服务器中部署了相同的DEBUG=True,它在行中抛出了多值dictKeyError,如果(t.otp==int(request.POST['otp']):。最初t.opt设置为生成的值,一旦用户
if(t.otp==int(request.POST['otp']):
匹配该模型,其中t
是一个模型对象。这个很好用。为了测试,我在heroku服务器中部署了相同的DEBUG=True
,它在行中抛出了多值dictKeyError
,如果(t.otp==int(request.POST['otp']):
。最初t.opt
设置为生成的值,一旦用户输入正确的OTP和寄存器,它将重新初始化为0。请注意代码中的注释
,该注释对问题进行了更详细的解释
我的views.py
如下所示(我删除了一些不需要减少行数的elif部分)
上述代码在
localhost
中运行良好,而在heroku
中运行失败。我曾在生产中使用过heroku postgres。我可以从您的代码中思考几个问题。1) 代码中的send\u mail
可能会引发异常。2) 你试过了,只是方块太大了。3) 您的Exception块不是非常具体,如果它是为此编写的,那么它应该只捕获特定的异常。4) 使用request.POST.get('pass2')
和类似方法,如果某个值可能不存在,则返回该值或None
。5) 你有一个观点处理两件事!理想情况下,这应该是两个视图。@AbdulAzizBarkat是的,我可能会更改它,但我的观点是,这在localhost
中完全可以,但在heroku
中则不行。除了:(就在t=temp.objects.get(name=uname)
之前)尝试编写除了MultiValueDictKeyError:
(来自django.utils.datastructures导入多值DictKeyError
)。您可能会遇到其他错误,这是您需要解决的实际错误。
def regsub(request):
if(request.method=="POST"):
uname = request.POST['username']
fname = request.POST['fname']
lname = request.POST['lname']
email = str(request.POST['email'])
pass1 = request.POST['pass1']
try: **#this tries to get the values pass1 and pass 2 whereas except gets the value otp**
if(request.POST['pass1']==request.POST['pass2']):
dictpass = {
'username':uname,
'fname':fname,
'lname':lname,
'email':email,
'password':pass1,
}
the_otp = r.randint(100000,999999)
try:
t=temp.objects.create(name=uname,otp=the_otp)
t.save()
except(IntegrityError):
return render(request,'register.html',{'flag':True,'msg':"Username already exits! Please try again."})
sub = "OTP for registration"
msg = "Some Message " + the_otp
from_email = settings.EMAIL_HOST_USER
to_email = [request.POST['email'],]
send_mail(sub,msg,from_email,to_email)
messages.info(request,"Password Verified! Please Enter the OTP sent to your email.")
return render(request,'register.html',dictpass)
except:
t = temp.objects.get(name=uname)
if (t.otp == int(request.POST['otp'])): **#the flow directly hits here after saving the otp in the model(send_mail part is not executed in try), also throws MultiValueDictKeyError**
user = User.objects.create_user(username=uname, first_name=fname, last_name=lname, email=email, password=pass1)
t.otp = 0
t.save()
user.save()
task.save()
sub = "Account creation successful"
msg = "Some Congrats message"
from_email = settings.EMAIL_HOST_USER
to_email = [request.POST['email'],]
send_mail(sub,msg,from_email,to_email)
messages.info(request,"Account has been created Successfully!")
return render(request,'login.html')
else:
return render(request,'register.html',{'flag':True})