Redirecting to a 404 page in Django

Sat, Apr 4, 2009

Tech Tips

There are a few ways to redirect to a 404 page (or page not found error) in Django. The easiest way is to raise Django’s built in 404 exception, like so:

from django.http import Http404

def myView(request, param):
  if not param:
    raise Http404

  return render_to_response('myView.html')

You can add a file called 404.html to your templates folder and Django will use this content to display to users during 404 errors.

If you want something a little more raw, you could do this:

from django.http import HttpResponseNotFound

def myView(request, param):
  if not param:
    return HttpResponseNotFound('<h1>No Page Here</h1>')

  return render_to_response('myView.html')

By default, if a url is not found in urls.py and ‘DEBUG = False’ in your settings.py, Django will redirect the user to a 404 page.

Here is a reference for returning errors in views and more detail on Request and Response objects.

Bookmark and Share
, , ,

Comments are closed.