异常:匹配查询不存在
Exception: Matching query does not exist
我正在尝试为请求忘记密码的用户生成令牌。我有一个模型来处理和存储这个。
models.py
class ForgetPassword(models.Model):
user = models.ForeignKey(CustomUser, on_delete= models.CASCADE)
forget_password_token = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add= True)
def __str__(self):
return self.user.email
处理请求的视图函数如下
views.py
def forget_password(request):
try:
if request.method == 'POST':
user_email = request.POST.get('email')
if CustomUser.objects.filter(email = user_email).exists():
user_obj = CustomUser.objects.get(email = user_email)
name = user_obj.full_name
plan = user_obj.plan
print("\n this is the user : ", user_obj, " this is its name : ", name,"\n")
token = str(uuid.uuid4())
fp = ForgetPassword.objects.get(user = user_obj)
fp.forget_password_token = token
fp.save()
forget_password_mail.delay(user_email, name, token)
messages.info(request, 'An email has been sent to your registered email.')
return redirect('forget-password')
else:
messages.info(request, 'User does not exist')
return redirect('forget-password')
except Exception as e:
print("\nthe exception is comming from forget_password : ", e, "\n")
return render(request, 'fp_email_form.html')
所以,在这里我试图首先从我的 CustomUser 模型中获取 user_obj 中的用户,然后我试图在 ForgetPassword 模型中获取相同的用户并针对该用户存储令牌。但我收到以下异常
ForgetPassword matching query does not exist.
不对的地方请指正或指正。
您没有与您尝试获取的用户对象关联的 ForgetPassword 对象,
fp = ForgetPassword.objects.get(user = user_obj)
相反,您应该使用 get_or_create
.
我正在尝试为请求忘记密码的用户生成令牌。我有一个模型来处理和存储这个。
models.py
class ForgetPassword(models.Model):
user = models.ForeignKey(CustomUser, on_delete= models.CASCADE)
forget_password_token = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add= True)
def __str__(self):
return self.user.email
处理请求的视图函数如下
views.py
def forget_password(request):
try:
if request.method == 'POST':
user_email = request.POST.get('email')
if CustomUser.objects.filter(email = user_email).exists():
user_obj = CustomUser.objects.get(email = user_email)
name = user_obj.full_name
plan = user_obj.plan
print("\n this is the user : ", user_obj, " this is its name : ", name,"\n")
token = str(uuid.uuid4())
fp = ForgetPassword.objects.get(user = user_obj)
fp.forget_password_token = token
fp.save()
forget_password_mail.delay(user_email, name, token)
messages.info(request, 'An email has been sent to your registered email.')
return redirect('forget-password')
else:
messages.info(request, 'User does not exist')
return redirect('forget-password')
except Exception as e:
print("\nthe exception is comming from forget_password : ", e, "\n")
return render(request, 'fp_email_form.html')
所以,在这里我试图首先从我的 CustomUser 模型中获取 user_obj 中的用户,然后我试图在 ForgetPassword 模型中获取相同的用户并针对该用户存储令牌。但我收到以下异常
ForgetPassword matching query does not exist.
不对的地方请指正或指正。
您没有与您尝试获取的用户对象关联的 ForgetPassword 对象,
fp = ForgetPassword.objects.get(user = user_obj)
相反,您应该使用 get_or_create
.