如果他们的配置文件角色值设置为“0”,我希望使用自定义中间件将用户重定向到他们的配置文件角色。
以下是我正在使用的当前代码,但会导致 302 重定向循环。这是基于我在互联网上找到的其他示例,但没有找到修复方法。
任何想法都会受到极大的重视。
from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponseRedirect
class UserRoleMiddleware(MiddlewareMixin):
def __init__(self, get_response):
self.get_response = get_response
def process_request(self, request):
redirect_url = '/role/'
if request.user.is_authenticated and request.user.profile.role == '0':
print('user must define a role')
return HttpResponseRedirect(redirect_url)
return None
回复:
[23/Oct/2021 23:00:50] "GET /role/ HTTP/1.1" 302 0
user must define a role
[23/Oct/2021 23:00:50] "GET /role/ HTTP/1.1" 302 0
user must define a role
[23/Oct/2021 23:00:50] "GET /role/ HTTP/1.1" 302 0
user must define a role
[23/Oct/2021 23:00:50] "GET /role/ HTTP/1.1" 302 0