About Catching Exceptions
When using try...except
, always define the exception type. Otherwise you might miss unexpected errors and can direct the logical flow incorrectly.
from django.core.exceptions import (
ObjectDoesNotExist, MultipleObjectsReturned
)
try:
rating = Post.objects.get(
slug=slug, user=request.user,
)
except ObjectDoesNotExist as e:
print("Post not found.")
except MultipleObjectsReturned as e:
print("Database integrity error.")
Tips and Tricks Programming Wisdom Django 5.x Django 4.2 Django 3.2 Django 2.2 Python 3
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.