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.
-
Deactivate `DEBUG`. That would do that. – spalac24 May 14 '15 at 03:54
4 Answers
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.

- 1
- 1

- 2,729
- 2
- 26
- 29
-
Thanks, but is there a way I can do the 404 handling without debug=false, because it is breaking my css as the static files are not loaded – Ankan Kumar Giri May 14 '15 at 08:39
-
@AnkanKumarGiri This is explained greatly in [this](http://stackoverflow.com/questions/5836674/why-does-debug-false-setting-make-my-django-static-files-access-fail) thread. Make sure to read all answers. – moonstruck May 14 '15 at 10:34
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.

- 1
- 1

- 946
- 7
- 22
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.

- 179
- 13
Go to your project settings.py
and set DEBUG = True
to DEBUG = False
Then Django redirects all NOT set patterns to not found.
In additional if you want to customize 404 template , in your project urls.py
set
handler404 = 'app.views.404_view'
then in your projects view.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
and Finally, in your templates
add 404.html
and fill it with what you want to show end user.

- 7,931
- 11
- 67
- 103