You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django3.2.8自定义中间件触发302重定向循环问题求解

问题根因

你的中间件未对重定向目标路径做豁免判断,当用户profile.role为0时,即便是访问角色设置页/role/也会再次触发重定向规则,导致无限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/'
        # 可根据业务需求增减豁免路径,比如登出页、公共接口、静态资源路径等
        exempt_paths = [
            redirect_url,
            '/logout/',
        ]
        # 当前请求属于豁免路径时直接跳过校验
        if request.path in exempt_paths:
            return None
            
        if request.user.is_authenticated and request.user.profile.role == '0':
            print('user must define a role')
            return HttpResponseRedirect(redirect_url)

        return None
额外优化建议
  • 建议使用Django的reverse函数生成路径,避免硬编码路径修改后中间件失效,比如redirect_url = reverse('role-setting'),前提是你给/role/的路由配置了name='role-setting'
  • 如果profile是和User模型的一对一关联,建议增加hasattr(request.user, 'profile')判断,避免部分未生成关联profile的用户访问时抛出AttributeError
  • 如果站点有不需要登录校验的公共页面、API接口,也可以统一加到豁免路径列表中

内容的提问来源于stack exchange,提问作者Franna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 14:06:00