Summary (Description):
Currently, django.shortcuts.get_object_or_404()
raises a hardcoded 404 message when an object is not found. Customizing this message requires wrapping it in a try/except
, which adds unnecessary repetition and breaks the DRY principle.
Proposal:
Introduce an optional msg
parameter to get_object_or_404()
, allowing custom 404 messages:
obj = get_object_or_404(MyModel, pk=some_id, msg="Custom not found message")
This change would:
- Enable custom error messages without needing
try/except
blocks. - Be backwards-compatible, defaulting to the current behavior if
msg
is not provided. - Align with Django’s other customizable exceptions (e.g.,
ValidationError
,PermissionDenied
).
Justification:
- Reduces repetitive code in views and APIs.
- Enhances flexibility for more meaningful 404 messages.
- Keeps Django’s philosophy of offering customizable error handling.
Request for Community Feedback:
Would love to hear thoughts from the community on whether this change would be useful, or if there are other considerations we should take into account before moving forward with a PR.