如何验证输入的电子邮件是否已经存在于数据库?



我有一个问题与程序我试图开发。我有一个功能,将发送OTP代码给用户,当他们要求登录。OTP代码应通过电子邮件发送给注册用户。问题是,我的代码现在接受每一封电子邮件,它不验证来自数据库的用户。我该怎么做呢?

已更新新代码!我更新了我以前发布的代码,因为最初我在获得OTP方面也有问题。有人帮我指出了我的错误,我纠正了他们。但现有的电子邮件验证仍然没有运气。请帮助!

这是我更新的脚本

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type='text/javascript'>
{% block title %}
{% endblock %}

{% block content %}
<h1>OTP Verification Page</h1>
<br>
<br>
<p>
</script>
<div id="email_div" style="display: block;" >
<label for="email">Email</label>
<input type="text" name="email" id="email">
<button  onclick="ajax_send_otp()">Send OTP</button>
</div>
<div id="verify_text_div"></div>
<div id="otp_div" style="display: none;" >
<label for="email">OTP</label>
<input type="text" name="otp" id="otp">
<button  onclick="verify_otp()">Verify</button>
</div>
</p>
{% endblock %}
<script>
var otp_from_back="";
function ajax_send_otp(){
document.getElementById("email_div").style.display='none';
email = document.getElementById("email");
$.post("/send_otp",
{
"email":email.value,
"csrfmiddlewaretoken":"{{csrf_token}}"
},
function(data, status){
if(status=="success"){
otp_from_back = data;
document.getElementById("otp_div").style.display='block';
}
}
);
}
function verify_otp(){
var user_otp=document.getElementById("otp").value;
if (user_otp==otp_from_back){
document.getElementById("verify_text_div").style.color="green";
document.getElementById("verify_text_div").innerHTML="OTP Verified";
setTimeout(window.location.assign("http://127.0.0.1:8000/login/"),2000);
document.getElementById("otp_div").style.display="none";
document.getElementById("form_div").style.display="block";
}
else{
document.getElementById("verify_text_div").style.color="red";
document.getElementById("verify_text_div").innerHTML="Try Again!!";
}
}
</script>

这是我更新的views。py文件

def otp_verification(request):
return render(request, 'otp.html')

def generateOTP():
digits = "0123456789"
OTP = ""
for i in range(4):
OTP += digits[math.floor(random.random() * 10)]
return OTP

def send_otp(request):
email = request.GET.get("email")
print(email)
o = generateOTP()
#email = EmailMessage(
#   subject='Nithya FYP OTP',
#  body= ('OTP request', o),
# from_email=EMAIL_HOST_USER,
#to=[email],
#)
#mail.send()
print(o)
return HttpResponse(o)

尝试验证您的电子邮件并检查该电子邮件是否存在于您的数据库中。

email = request.POST['email']
if validate_email(email) and User.objects.filter(email=email).exists():
...
else:
...

最新更新