How to display a custom error page for HTTP status 405 (method not allowed) in Django when using @require_POST

前端 未结 3 1145
孤独总比滥情好
孤独总比滥情好 2021-02-05 20:40

My question is simple, how do I display a custom error page for HTTP status 405 (method not allowed) in Django when using the @require_POST decorator?

I\'m

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-05 20:50

    You have to write custom Django middleware. You can start with this one and extend it to check if 405.html file exists and so on:

    from django.http import HttpResponseNotAllowed
    from django.template import RequestContext
    from django.template import loader
    
    
    class HttpResponseNotAllowedMiddleware(object):
        def process_response(self, request, response):
            if isinstance(response, HttpResponseNotAllowed):
                context = RequestContext(request)
                response.content = loader.render_to_string("405.html", context_instance=context)
            return response
    

    Check docs if you don't know how to install middleware:

    http://docs.djangoproject.com/en/dev/topics/http/middleware/

    You can also check this article:

    http://mitchfournier.com/2010/07/12/show-a-custom-403-forbidden-error-page-in-django/

提交回复
热议问题