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:
- #exceptions.py
- class ProfileHttp404(Exception):
- pass
- #views.py
- from exceptions import ProfileHttp404()
-
- def profile(request, username):
- try:
- user = User.objects.get(username=username)
- except:
- raise ProfileHttp404()
- # profile page code
Middleware to the rescue!
- #middleware.py
- from exceptions import ProfileHttp404
- from django.views.defaults import page_not_found
- from django.http import HttpResponseNotFound
-
- class ProfileHttp404Middleware(object):
- """
- Make sure profile related 404 pages renders our specific template
- """
- def process_exception(self, request, exception):
- if isinstance(exception, ProfileHttp404):
- return HttpResponseNotFound(page_not_found(request, template_name='profiles/errors/404.html'))
- return None
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



Leave a Comment :
Leave a Comment