[Answered ]-Django – get_object_or_404 returns 500 instead of 404

2👍

I encountered the same problem and Milano Slesarik’s comment helped me figure out the solution. It turns out that I recently assigned a custom 404 handler but didn’t do it correctly.

Here’s what I did right:
add following line to urls.py. No need to add from django.conf.urls import handler404:

handler404 = views.error404

Here’s what I did wrong. In my views.py I added this function:

def error404(request):
    return HttpResponseNotFound('custom 404 not found')

But I forgot to import HttpResponseNotFound in views.py:

from django.http import HttpResponse, HttpResponseNotFound

So it was raising an exception. But since I just set DEBUG=False I couldn’t see the error. I just saw the 500 response code.

Hope that helps someone!

with the following line in urls.py:

handler404 = 'views.error404'

0👍

If the project has several apps with their own urls.py you should add handler404 = 'app_name.views.my_handle404' to to the root url conf (that exists in project directory by default)

0👍

For me the only solution that worked (Django 3.7) dev/prod is here

Please see @elano7 answer

Leave a comment