Django 500 message in custom template

风流意气都作罢 提交于 2019-12-09 15:10:19

问题


I have a 500.html template which gets loaded whenever my app explodes but I wanted to know if there's any way I can output the exception's message in the template?

So if I do this:

raise Exception("You broke it!")

This will load 500.html when the DEBUG flag is set to True but how can I access the exception message in the template? Something like:

{{ exception.message }}

Many thanks.

G


回答1:


Have a look at this answer:

How do I include a stacktrace in my Django 500.html page?

It's not good to pass the exception to your template/user as it might show some inside workings that you don't want available to the outside, but if you really need to, you could write your own 500 view, grabbing the exception and passing it to your 500 template

views.py

def custom_500(request):
    t = loader.get_template('500.html')
    type, value, tb = sys.exc_info(),
    return HttpResponseServerError(t.render(Context({
    'exception_value': value,
})))

somewhere in urls.py

handler500 = 'mysite.views.my_custom_error_view'

template

{{ exception_value }}

more about it here: https://docs.djangoproject.com/en/1.6/topics/http/views/#the-500-server-error-view




回答2:


I know this is an old thread, but I just wanna to make it clear:

The answer is correct if you want a custon view! The default view will load a 500.html (also 404.html and others), from the main templates directory of your project if it's there.

So, if all you need is to change static page content, like insert some images in your error page, all you have to do is to create a template file at this place.



来源:https://stackoverflow.com/questions/6190254/django-500-message-in-custom-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!