Allow Customizable 404 Messages via msg Parameter in get_object_or_404()

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.

Welcome @PhenixDhinesh !

The first issue you’re going to face is the possibility that whatever keyword you try to use for the parameter could conflict with a parameter that needs to be passed through to the query being executed. (What if someone has a model with a field named msg?)

If you’re really going to find this helpful, you can always create your own version of the function and call it instead of the Django-provided function. Your function can either call the Django function or implement the base functionality itself - depending upon how you want to handle your extensions.

Fair Point. i haven’t though about it. thank for pointing out

We can use a name safe uuid(with a favorable name) if we really want. Just suggesting.