Home > Enterprise >  How do I redirect from require_http_methods without using middleware?
How do I redirect from require_http_methods without using middleware?

Time:09-21

I used a @require_http_methods decorator in my code for the logout page, but I can't wrap my head around the proper way to redirect a user on the method error.

It is suggested to create a middleware there: django require_http_methods. default page

But I wonder if there is a simpler way?


(I know I can just check for a method manually like this: if method == 'POST') But I want to know what the best practice is.

CodePudding user response:

You can make a custom decorator based on the @require_http_methods decorator [Django-doc] by altering its source code [GitHub], such that it redirects instead of returning a HTTP 405 error:

from django.shortcuts import redirect

def require_http_methods_redirect(request_method_list, redirect_to=None):
    def decorator(func):
        @wraps(func)
        def inner(request, *args, **kwargs):
            if request.method not in request_method_list:
                if redirect_to is not None:
                    return redirect(redirect_to)
                else:
                    response = HttpResponseNotAllowed(request_method_list)
                log_response(
                    'Method Not Allowed (%s): %s', request.method, request.path,
                    response=response,
                    request=request,
                )
                return response
            return func(request, *args, **kwargs)
        return inner
    return decorator

then in your logout view, you can specify a redirect_to:

from django.urls import reverse_lazy

@require_http_methods_redirect(['POST'], redirect_to=reverse_lazy('name-of-some-view'))
def my_view(request):
    # …
  • Related