Exception: Matching query does not exist

I am trying to generate a token for users requesting for forget password. I have a model to handle and store this.


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

The view functions that handles the request are below


def forget_password(request):


        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

                forget_password_mail.delay(user_email, name, token)
                messages.info(request, 'An email has been sent to your registered email.')
                return redirect('forget-password')  
                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')

So, here I am trying to get the user first in user_obj from my CustomUser model and then I am trying to get the same user in the ForgetPassword model and store the token against that user. But I am getting the below exception

ForgetPassword matching query does not exist.

Please suggest or correcct me where I am wrong.


You do not have a ForgetPassword object associated with the user object you are trying to fetch at,

fp = ForgetPassword.objects.get(user = user_obj) Instead, you should use get_or_create.

reference link