我在logout頁面的代碼中使用了一個@require_http_methods裝飾器,但我無法理解在方法錯誤時重定向用戶的正確方法。
有人建議在那里創建一個中間件。django require_http_methods. default page
但我想知道是否有一個更簡單的方法?
(我知道我可以像這樣手動檢查一個方法。if method == 'POST')但我想知道最佳做法是什么。
uj5u.com熱心網友回復:
你可以基于@require_http_methods裝飾器[Django-doc]制作一個自定義裝飾器,改變其源代碼[GitHub],使其重定向而不是回傳一個HTTP 405錯誤:
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=回應。
request=請求。
)
return 回應
return func(request, *args, **kwargs)
return inner
return decorator
然后在你的注銷視圖中,你可以指定一個redirect_to:
from django.urls import reverse_lazy
@require_http_methods_redirect(['POST'/span>]。redirect_to=reverse_lazy('name-of-some-view'))))
def my_view(request)。
# ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/323530.html
標籤:
