Django重定向到/ accounts / profile

时间:2018-07-30 06:48:03

标签: django python-3.x django-forms django-templates django-views

我编写了一些中间件,该中间件限制了对所有URL(受豁免的URL除外)的访问。用户只有登录后才能访问所有URL,如果未登录,则用户只能访问豁免的URL。当用户登录后尝试访问其中一个免税网址时,即重定向发生(即重定向到/ accounts / profile)时,就会出现问题。我该如何解决这个问题?

我的中间件

from django.conf import settings
from django.urls import reverse
from django.shortcuts import redirect
from django.contrib.auth import logout
import re

EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
    EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS]


class LoginRequiredMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        assert hasattr(request, 'user')
        path = request.path_info.lstrip('/')

        url_is_exempt = any(url.match(path) for url in EXEMPT_URLS)

        if path == reverse('logout_success').lstrip('/'):
            logout(request)

        if request.user.is_authenticated() and url_is_exempt:
            return redirect(settings.LOGIN_REDIRECT_URL)
        elif request.user.is_authenticated() or url_is_exempt:
            return None
        else:
            return redirect(settings.LOGIN_URL)

设置文件中的豁免URL。

LOGIN_URL = '/user_account/login/'

LOGIN_EXEMPT_URLS = (
    r'^$',
    r'^tenders/',
    r'^pricing/',
    r'^articles/',
    r'^contact_us/',
    r'^user_account/logout_success/$',
    r'^user_account/subscribe/$',
    r'^user_account/auth/$',
    r'^user_account/password_reset/$',
    r'^user_account/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
    r'^user_account/subscribe/(?P<billing_cycle>\d)/(?P<pk>\d+)/$',
    r'^user_account/password_reset/done/$',
    r'^user_account/reset/done/$',
    r'^user_account/auto_complete_search/$',
)

用户登录后,我尝试访问r'^ user_account / auto_complete_search/$'。

1 个答案:

答案 0 :(得分:0)

在上面的第二个if语句的中间件代码中找到了问题所在。即

if request.user.is_authenticated() and url_is_exempt:
            return redirect(settings.LOGIN_REDIRECT_URL)

我将“ return redirect(settings.LOGIN_REDIRECT_URL)”行更改为“不返回任何内容”,问题已解决。