5

When i read Django documentation i found only handlers for: 400, 403, 404, 500 errors.

Why 405 error handler doesn't exists but decorators like require_POST() is in common use?

The point is, what is proper way to create custom error page for Method Not Allowed error ?


I resolve my problem using Django Middleware maybe this will help someone

from django.http import HttpResponseNotAllowed
from django.shortcuts import render


class HttpResponseNotAllowedMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)

        if isinstance(response, HttpResponseNotAllowed):
            return render(request, '405.html', status=405)

        return response
mkfb
  • 51
  • 2
  • Check this - https://stackoverflow.com/questions/22983222/405-post-method-not-allowed – dmitryro Mar 07 '18 at 22:28
  • Problem is not that why i have 405 error - i know why. Problem is how to handle 405 error to custom error page. – mkfb Mar 08 '18 at 11:02
  • You can create a custom handler - If you use Django Rest Framework something like http://www.django-rest-framework.org/api-guide/exceptions/ or use a method like https://medium.com/@mwhitt.w/restful-error-messages-with-django-537047892dff - create a custom handling function and assign status there. – dmitryro Mar 08 '18 at 11:20

1 Answers1

0

If you want a different response for each view, you can overwrite your function like:

class someView(View):
    ....

    def http_method_not_allowed(self, request, *args, **kwargs):
        return HttpResponse("Not available")

If you wanna know what the function does check https://github.com/django/django/blob/master/django/views/generic/base.py#L90

Mauricio Cortazar
  • 3,263
  • 2
  • 13
  • 25