Hi there,
I am working on a Django app where I need to check exceptions a lot and then throw them in models.py
and views.py
. My question is, let’s say I am in a view, and I need to catch and throw an exception in the middle of that view. How do I make Django keep executing the rest of the view even after throwing the exception?
For example, I have the following views.py
(only some methods and relevant details are shown):
class PasswordResetRequest(View):
def get(self, request):
password_reset_request_form = PasswordResetForm()
context = {
"title": "Reset Your Password",
"password_reset_request_form":
password_reset_request_form,
}
return render(request, "accounts/password-reset.html", context)
def post(self, request):
password_reset_request_form = PasswordResetForm(request.POST)
context = {
"title": "Reset Your Password",
"password_reset_request_form": password_reset_request_form,
}
if password_reset_request_form.is_valid():
try:
user = User.objects.get(
email=password_reset_request_form\
.cleaned_data["email"]
)
except Exception as ex:
raise Exception("ERROR: Could not get User \
instance because email enetred does not \
exist in the database") # AFTER THIS EXCEPTION IS RAISED, I WANT DJANGO TO EXECUTE THE REST OF THE VIEW. HOW CAN I MAKE IT POSSIBLE?
else:
user = None
if user is None:
result = self.post_decision(user, request, context)
return result["return"]
status_message = user.send_password_reset_email()
result = self.post_decision(
user,
request,
context,
status_message
)
return result["return"]
else:
messages.error(
request,
f"ERROR: You did not fill all the fields of form."
)
return render(
request,
"accounts/password-reset.html",
context
)
Any help will be appreciated.