我已参考此网站http://onecreativeblog.com/post/59051248/django-login-required-middleware
上分享的代码进行登录所需的中间件。问题是它正在运行重定向循环。
import re
from django.conf import settings
from django.urls import reverse
from django.shortcuts import redirect
from django.contrib.auth import logout
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('/')
if not request.user.is_authenticated():
if not any(url.match(path) for url in EXEMPT_URLS):
return redirect(settings.LOGIN_URL)
我已经研究过stackoverflow并尝试了几乎所有的解决方案但是徒劳无功。 设置网址
LOGIN_REDIRECT_URL='/blog/index/'
LOGIN_EXEMPT_URLS= (
r'^blog/signup/$',
r'^blog/logout/$',
)
任何帮助将不胜感激!提前谢谢。