首页 > 解决方案 > 在 Django 中使用中间件重定向 ERR_TOO_MANY_REDIRECTS

问题描述

我编写了这个程序,以便在满足某些条件时将用户移动到我的目标页面。

这是我的自定义 Djangomiddleware

def check_userprofile_middleware(get_response):
    def middleware(request):
        response = get_response(request)
        if request.user.is_authenticated:
            # Profile conditions goes here. 
            if profile_condition:
                return redirect(reverse('base:edit_user_profile'))
        return response
    return middleware

如果我使用returninif语句,它会重定向到 'base:edit_user_profile' url,但之后我在浏览器上看到此错误:

This page isn’t working
127.0.0.1 redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS

如果我不使用returninif语句,一切都会正确,除了重定向!

这有什么问题?

标签: pythondjangodjango-middleware

解决方案


通过@gelonida 的提示,我收到了答案。我确实添加了这一行,问题得到解决:

        while not (request.path == reverse('base:edit_edupanel_user_profile')):
            return redirect(reverse('base:edit_edupanel_user_profile'))

推荐阅读