David.dev

Coding & More 📱 Apps ℹ️ About

Django 3 Redirect all 404 to homepage

11-Sep-2021 - django, python

Handling 404 pages in Django is very easy: just add a 404.html file inside your templates folder (e.g. inside your app) and it will work just fine.

But what if you want, in stade of displaying a 404 page, you want to redirect all 404 traffic to your homepage?

in the main urls.py (not the one inside your app folder but the main urls.py) add

 from app import views
 handler404 = 'myappname.views.view_404'

then in views.py add the following:

 from django.http import HttpResponseRedirect
 def view_404(request, exception=None):
     return HttpResponseRedirect("/")

this can be useful in case you just want the missing / not found page to redirect to the home page directly in lieu of displaying a 404.html page first.

👏

26