0

I'm developing one Django project which contains multiple apps. I want a common 404 and 500 error page for all the applications. How should i do it?

I've implemented individual error pages for each app & It's working fine. But I want a common page which should be placed in my main project folder.

Amlanjyoti
  • 85
  • 2
  • 8
  • Aren't you looking for [this](https://stackoverflow.com/a/37611184/9733868)? – Pedram Parsian Nov 15 '19 at 09:23
  • PedramParsian yes I'm looking for this only n I've implemented also.In the given example he has created different error pages for a single app. But my question is in my case I've 5 different apps in the project & I want a single error page to be created which should be populated for all the django apps.Also it should be present in my project folder not in app(mysite as per the example) folder. – Amlanjyoti Nov 15 '19 at 09:29
  • So if you put `handler404` (and so for others...) in your **main** `urls.py` (the one besides `settings.py`), it will be used for all of your apps. – Pedram Parsian Nov 15 '19 at 09:31
  • Ok...I'm trying the same... – Amlanjyoti Nov 15 '19 at 09:37

2 Answers2

0

In your templates directory create templates custom404.html and custom500.html

Add this to your urls.py at the bottom if application specific or in urls.py where you include urls to other apps

handler404 = 'custom_views.handler404'
handler500 = 'custom_views.handler500'

And define views like this in custom_views file in root once

from django.shortcuts import render_to_response

def handler404(request, *args, **kwargs):
    response = render_to_response('custom404.html', context = {})
    response.status_code = 404
    return response


def handler500(request, *args, **kwargs):
    response = render_to_response('custom500.html', context={})
    response.status_code = 500
    return response

This will route your 404,500 url to the template views there your are building a template and rendering it

Yugandhar Chaudhari
  • 3,831
  • 3
  • 24
  • 40
  • I got your solution. One doubt I've..So that custom_view do i have to write it in my base project in Django?Also I've to place this view n functions in all my apps.. right? – Amlanjyoti Nov 15 '19 at 09:41
  • Not in root necessarily you can keep it in module wherever you like. Just give the path to module `handler404 ='somefolder.custom_views.handler404'` – Yugandhar Chaudhari Nov 15 '19 at 09:46
0

The simplest way to do this is to create a templates directory in your BASE_DIR i.e. the directory containing manage.py
Add the path to that directory in your settings

TEMPLATES = [
    {
        ...
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        ...
]

Then just simply create your error pages in templates directory.
Example: If you want to create a page for error 404, then create a file named 404.html inside the templates directory.

shan_1.0
  • 87
  • 1
  • 10