Search code examples
pythondjangocustom-error-pages

Create custom 404 error for each app on my django project?


is there a way to create multiple custom errors templates for each app on my Django project, I mean, in my project I got 3 apps I will show 3 different customs 404 error per each app.

Right now I'm showing the same 404 error page for my back office app and front office.


Solution

  • Create a custom error view and assign it to handler404 variable in your root urls.py:

    from django.views.defaults import page_not_found
    
    def my_error_404(request, exception):
        template_name = '404.html'
        if request.path.startswith('/backoffice/'):
            template_name='backoffice/404.html'
        elif request.path.startswith('/frontoffice/'):
            template_name='frontoffice/404.html'
        return page_not_found(request, exception, template_name=template_name)
    

    This code is for django 1.9. If you use django <= 1.9 then remove the exception parameter from the view.