Search code examples
djangodjango-templateshttp-status-code-404

how show personalized error with get_object_or_404


I would like to know how to show personalized errors with the get_object_or_404 method. I don't want the normal Http404 pages, but I want to display a custom message with the message: the result is none.

Thanks :)


Solution

  • The get_object_or_404() is essentially a simple 5-line function. Unless you have some specific reason for using it, just do:

    try:
        instance = YourModel.objects.get(pk=something)
    except YourModel.DoesNotExist:
        return render_to_response('a_template_with_your_error_message.html')
    

    If for whatever reason you have to use get_object_or_404(), you can try putting it in a try: ... except Http404: ... block, but I honestly can't think of a plausible reason for that.