Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize Page not found (404) in django?

How I customize the error page in Django and where do I put my html for this page.

like image 928
user2169287 Avatar asked Mar 14 '13 10:03

user2169287


2 Answers

Just create a 404.html file in your project's root level templates directory.

like image 122
Jack Shedd Avatar answered Oct 04 '22 16:10

Jack Shedd


First you need to edit the settings.py to point to a templates folder: Django template Path

After you have your 404.htm inside the template folder, you can follow the instructions below:

It is important to inform the search engines that the current page is a 404. You do that by changing the http header. So here it is a good way to go:

Into your application's urls.py add:

# Imports
from django.conf.urls.static import static
from django.conf.urls import handler404
from django.conf.urls import patterns, include, url
from yourapplication import views

##
# Handles the URLS calls
urlpatterns = patterns('',
    # url(r'^$', include('app.homepage.urls')),
)

handler404 = views.error404

Into your application's views.py add:

# Imports
from django.shortcuts import render
from django.http import HttpResponse
from django.template import Context, loader


##
# Handle 404 Errors
# @param request WSGIRequest list with all HTTP Request
def error404(request):

    # 1. Load models for this view
    #from idgsupply.models import My404Method

    # 2. Generate Content for this view
    template = loader.get_template('404.htm')
    context = Context({
        'message': 'All: %s' % request,
        })

    # 3. Return Template for this view + Data
    return HttpResponse(content=template.render(context), content_type='text/html; charset=utf-8', status=404)

The secret is in the last line: status=404

Hope it helped!

I look forward to see the community inputs to this approach. =)

like image 23
Fabio Nolasco Avatar answered Oct 04 '22 16:10

Fabio Nolasco