[Fixed]-How show personalized error with get_object_or_404

25đź‘Ť

âś…

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.

👤Aram Dulyan

4đź‘Ť

As stated by michael, when using get_object_or_404 you cannot customize the message given on http 404. The message provided in DEBUG does offer information about the exception however: “No MyModel matches the given query.”

Check out the doc on this. There are three arguments: Model, *args, and **kwargs. The last two are used to build an argument for either get() or filter() on the Model.

The reason I wrote, however, is to address the question of why we would want to use a helper function such as get_object_or_404() instead of, for example, catching it with an exception like Model.DoesNotExist.

The later solution couples the view layer to the model layer. In an effort to relax this coupling we can take advantage of the controlled coupling offered in the django.shortcuts module[1].

👤user3842449

3đź‘Ť

That can’t be done with that shortcut. It will only raise a Http404 exception. Your best bet is a try catch if you want full control. Eg.

try:
    obj = Model.objects.get(pk = foo)
except:
    return HttpResponseRedirect('/no/foo/for/you')
    #or
    return render_to_response ...
👤michael

3đź‘Ť

And why exactly aren’t you using your server’s capeability to do just that?
get_object_or_404() is redirecting to the default 404 page right?
If you are on debug mode you won’t see it but when deployed django will just refer to the server’s 404 html page.

👤the_drow

Leave a comment