Home » Odeon Blogs » Liviu, Agile Bear »

Django Custom 404 for special cases

Django Custom 404 for special cases

Django makes it easy to handle the output of 404 pages for the website, just define 404handler in urls and thats it.
But what happens if you need to show a different template for some specific method? Simple, create your own custom exception instead of using Http404.

Assuming we need this done for profile pages, when accessing some url that is restricted, let's define a ProfileHttp404 exception:

  1. #exceptions.py
  2. class ProfileHttp404(Exception):
  3. pass
To use it, let's assume that this should happen when accessing the profile page of a user that does not exists:
  1. #views.py
  2. from exceptions import ProfileHttp404()
  3. def profile(request, username):
  4. try:
  5. user = User.objects.get(username=username)
  6. except:
  7. raise ProfileHttp404()
  8. # profile page code
Accessing the profile page now, it will not return a 404 HTTP code, but a 500 one. Obvious, since we are raising an Exception. There is one more missing piece in the puzzle, something to catch this exception and render our specific template.

Middleware to the rescue!
  1. #middleware.py
  2. from exceptions import ProfileHttp404
  3. from django.views.defaults import page_not_found
  4. from django.http import HttpResponseNotFound
  5. class ProfileHttp404Middleware(object):
  6. """
  7. Make sure profile related 404 pages renders our specific template
  8. """
  9. def process_exception(self, request, exception):
  10. if isinstance(exception, ProfileHttp404):
  11. return HttpResponseNotFound(page_not_found(request, template_name='profiles/errors/404.html'))
  12. return None
Don't forget to add the middleware in settings.py in MIDDLEWARE_CLASSES.

Now we have a generic 404 template for all the site and a profile specific 404 template rendered each time ProfileHttp404 is raised.


Category: Django


Tagged as: 404 custom django



Leave a Comment :

(required)


(required)




(required)




(required)






Leave a Comment


Page generated in: 0.16s