[Django]-How to properly setup custom handler404 in django?

19👍

As we discussed, your setup is correct, but in settings.py you should make DEBUG=False. It’s more of a production feature and won’t work in development environment(unless you have DEBUG=False in dev machine of course).

12👍

All the other answers were not up to date. Here’s what worked for me in Django 3.1:

urls.py

from django.conf.urls import handler404, handler500, handler403, handler400
from your_app_name import views

handler404 = views.error_404
handler500 = views.error_500

views.py

def error_404(request, exception):
   context = {}
   return render(request,'admin/404.html', context)

def error_500(request):
   context = {}
   return render(request,'admin/500.html', context)

Note, you will have to edit this code to reflect your app name in the import statement in urls.py and the path to your html templates in views.py.

👤devdrc

11👍

Debug should be False and add to view *args and **kwargs. Add to urls.py handler404 = 'view_404'

def view_404(request, *args, **kwargs):
return redirect('https://your-site/404')

If I didn’t add args and kwargs server get 500.

6👍

To render 404 Error responses on a custom page, do the following:

In your project directory open settings.py and modify DEBUG as follows:

    DEBUG = False

In the same directory create a file and name it views.py, insert the following code:

   from django.shortcuts import render

   def handler404(request, exception):
       return render(request, 'shop/shop.html')

Finally open urls.py file which is in the same project directory and add the following code:

   from django.contrib import admin
   from . import views

   handler404 = views.handler404

   urlpatterns = [
      path('admin/', admin.site.urls),
   ]

Leave a comment