Django - Custom Error Templates not rendering
I have some custom templates in my django app. But these are not being rendered and instead displays the basic template:
500 Internal Server Error
Exception inside application.
Daphne
Edit: If I move my dev.py (used on local to DEBUG = False), then the template is rendered.
This is my setup:
Views.py (app level: main):
def custom_500(request):
return render(request,'main/500.html', status=500)
templates (app level: main with path: templates->main->500html)
500.html custom template file
urls.py (project level)
from main.views import custom_400, custom_500
from django.conf.urls import handler500, handler400
handler500 = 'main.views.custom_500'
settings (folder) staging.py:
DEBUG = False
ALLOWED_HOSTS = ['domainname.com' ]
SECURE_SSL_REDIRECT = True
I also have a base.py in my setting folder, but cannot see anything I should report on there.
I tried to list all the checks I have tried:
In heroku app shell:
print(settings.ALLOWED_HOSTS) # returned the domain name
print(settings.DEBUG) # returned false
print(os.getenv('DJANGO_SETTINGS_MODULE')) # mysite.settings.staging
print(settings.CSRF_COOKIE_SECURE) # true (just in case I would the app would be treated as non prod)
print(settings.SECURE_SSL_REDIRECT) # true (just in case I would the app would be treated as non prod)
and finally:
>>> from django.shortcuts import render
>>> from django.test import RequestFactory
>>> request = RequestFactory().get('/')
>>> render(request,'main/500.html', status=500)
#returned: <HttpResponse status_code=500, "text/html; charset=utf-8">
I am running out of idea, and I am sure its probably something simple.
I am hoping someone may have some suggestion.
There are probably several ways to land this, but below is what I do. While there could be some optimization to this, it works well so long as the error is within the django app and not with the webserver itself.
in urls.py: (don't see any difference here).
if not DEBUG: # i don't want custom error handling in my dev environment because i want to see the dump to help with troubleshooting.
handler500 = '<project>.views.custom_500'
in views.py: I see some differences here... don't know if they are necessarily material or not.
def custom_500(request, *args, **argv):
context = {'<load up the data i need to send to the custom template>',}
t = loader.get_template('error.html')
response = HttpResponseServerError(t.render(context))
response.status_code = 500 # need to set this to ensure flags the error and sends dump data to admins.
return response