Django 3.2 how to redirect 404 to homepage

Viewed 530

I did find a number of answers about 404 redirect for Django but mostly are referring to an older version of Django.

Here is what I have in Django 3.2.6 DEBUG is set to False to trigger the 404 behaviour

urls.py

 handler404 = views.view_404

views.py

 def view_404(request, exception=None):
     return HttpResponseRedirect("/")

No error in runserver but a 404 page still returns "Not Found

The requested resource was not found on this server.".

2 Answers

Try this:

urls.py

handler404 = 'myappname.views.view_404'

views.py

 def view_404(request, exception=None):
      return HttpResponseRedirect("/")

Note that to display a custom template you can simply create a template with named 404.html in your main templates directory. For clarifications you can read the documentation.

The problem you have is that you defined your handler404 in your app urls.py file.

You need to move it to the project urls.py file to get it working.

Related