Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect any urls to 404.html if not found in urls.py in django

How can I redirect any kind of url patterns to a created page "404.html" page if it doesn't exist in the urls.py rather than being shown the error by django.

like image 553
Ankan Kumar Giri Avatar asked May 14 '15 03:05

Ankan Kumar Giri


3 Answers

There is no need to change anything in your view or url. Just do these 2 steps, in your settings.py, do the following

DEBUG = False
ALLOWED_HOSTS = ["*"]

And in your app directory (myapp in this example), create myapp/templates/404.html where 404.html is your custom error page. That is it.

like image 159
Banks Avatar answered Nov 05 '22 23:11

Banks


Make a view that'll render your created 404.html and set it as handler404 in urls.py.

handler404 = 'app.views.404_view'

Django will render debug view if debug is enabled. Else it'll render 404 page as specified in handler404 for all types of pages if it doesn't exist.

Django documentation on Customizing error views.

Check this answer for a complete example.

like image 12
moonstruck Avatar answered Nov 06 '22 01:11

moonstruck


In your views.py, just add the following code (No need to change anything in urls.py).

from django.shortcuts import render_to_response
from django.template import RequestContext


def handler404(request):
    response = render_to_response('404.html', {},
                              context_instance=RequestContext(request))
    response.status_code = 404
    return response

Put a custom 404.html in templates directory.

source : click here

like image 2
kartikmaji Avatar answered Nov 05 '22 23:11

kartikmaji