Home > database >  Redirect all page not found to home page
Redirect all page not found to home page

Time:10-31

I would like to redirect all 404 pages to a home page. I try this but it don't work

app/views.py

from django.http import HttpResponse
from django.shortcuts import render, redirect

def home(request): return HttpResponse('<h1> HOME </h1>')

def redirectPNF(request, exception): return redirect('home')

app/urls.py

from . import views
urlpatterns = [ path('home', views.home, name="home"), ]

app/settings.py

handler404 = 'app.views.redirectPNF'
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
DEBUG = False

CodePudding user response:

Just Add this line in urls.py instead of settings.py
Everything else seems ok.

It is also mentioned in the django documentation that setting handler variables from anywhere else will have no effect. It has to be set from URLconf

The default error views in Django should suffice for most web applications, but can easily be overridden if you need any custom behavior. Specify the handlers as seen below in your URLconf (setting them anywhere else will have no effect).

app/urls.py

from . import views

handler404 = 'app.views.redirectPNF' # Added this line in URLconf instead of settings.py


urlpatterns = [ path('home', views.home, name="home"), ]
  • Related