简体   繁体   中英

How to override handler404 and handler505 error in django?

How do i override the handler404 and handler505 error in django? i already change the DEBUG TRUE into False in my settings.py.

this is my views.py

def Errorhandler404(request):
    return render(request, 'customAdmin/my_custom_page_not_found_view.html', status=404)

def Errorhandler500(request):
    return render(request, 'customAdmin/my_custom_error_view.html', status=500)

this is my urls.py

handler404 = customAdmin.views.Errorhandler404
handler500 = customAdmin.views.Errorhandler500
urlpatterns = [
     .....
]

this is the error

在此处输入图像描述

this is the documentation i follow

https://micropyramid.com/blog/handling-custom-error-pages-in-django/

You need to define a function that takes the exception parameter into account as well, as specified in the documentation on handler404 :

handler404

A callable, or a string representing the full Python import path to the view that should be called if none of the URL patterns match.

By default, this is django.views.defaults.page_not_found(). If you implement a custom view, be sure it accepts request and exception arguments and returns an HttpResponseNotFound .

You can ignore the parameter, or print information about the exception in the response:

def Errorhandler404(request):
    return render(request, 'customAdmin/my_custom_page_not_found_view.html', status=404)

def Errorhandler500(request):
    return render(request, 'customAdmin/my_custom_error_view.html', status=500)

Normally the ErrorHandler404 should return a HttpResponseNotFound response [Django-doc] :

from django.http import 
from django.template import loader

def Errorhandler404(request, exception):
    content = loader.render_to_string('customAdmin/my_custom_page_not_found_view.html', {}, request)
    return content

The ErrorHandler500 should return a HttpResponseServerError object [Django-doc] :

from django.http import 
from django.template import loader

def Errorhandler500(request):
    content = loader.render_to_string('customAdmin/my_custom_page_not_found_view.html', {}, request)
    return content

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM