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:

  1. from django.http import Http404  
  2.   
  3. def myView(request, param):  
  4.   if not param:  
  5.     raise Http404  
  6.   
  7.   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:

  1. from django.http import HttpResponseNotFound  
  2.   
  3. def myView(request, param):  
  4.   if not param:  
  5.     return HttpResponseNotFound('<h1>No Page Here</h1>')  
  6.   
  7.   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.