简体   繁体   English

Django 需要登录错误 ERR_TOO_MANY_REDIRECTS

[英]Django login required error ERR_TOO_MANY_REDIRECTS

My django application worked fine before using LoginRequiredMiddleware, after I used LoginRequiredMiddleware i have got this error.我的 django 应用程序在使用 LoginRequiredMiddleware 之前运行良好,在我使用 LoginRequiredMiddleware 之后出现此错误。

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

settings.py设置.py

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'login_required.middleware.LoginRequiredMiddleware',
# 'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

REPORT_BUILDER_ASYNC_REPORT = True
WSGI_APPLICATION = 'mymachine.wsgi.application'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
LOGIN_REDIRECT_URL = 'index'
LOGOUT_REDIRECT_URL = 'login'
LOGIN_URL = 'login'
CSRF_COOKIE_HTTPONLY = False

url.py url.py

urlpatterns = [
path('login/', LoginView.as_view(), name='login'),
path('logout/', LogoutView.as_view(), name='logout'),
path('', IndexView.as_view(), name='index'),
]

view.py视图.py

class LoginView(CreateView):
"""
Login
"""
template_name = "registration/login.html"
defaults = dict()

def __init__(self, **kwargs):
    super(LoginView, self).__init__(**kwargs)

def on_create(self, request, *args, **kwargs):
    return render(request, self.template_name, self.defaults)

def init_component(self, request):
    logout(request)
    self.defaults['name_space'] = reverse('auth')
    self.defaults['form'] = LoginForm

def get(self, request, *args, **kwargs):
    self.init_component(request)
    return self.on_create(request, *args, **kwargs)

def post(self, request, *args, **kwargs):
    form = LoginForm(request.POST)
    if form.is_valid():
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user:
            login(request, user)
            request.session["company_id"] = 1
            return redirect(settings.LOGIN_REDIRECT_URL)
        elif user is None:
            context = {'name_space': reverse('auth'), 'form': LoginForm,
                       'message': _("username or password is incorrect"), 'add': 'try Again'}
            return render(request, 'registration/login.html', context)

This is the url that appears in chrome.这是 chrome 中出现的 url。

http://127.0.0.1:4050/login/?next=/login/ http://127.0.0.1:4050/login/?next=/login/

I have tried must of the answers in the web but none is worked, please help to solve this, Thank you in advance.我已经尝试过 web 中的答案,但没有一个有效,请帮助解决这个问题,提前谢谢你。

Middleware works for every request/response, since you added LoginRequiredMiddleware which will redirect to login page but you are not authenticated so again you will be redirected to login page.中间件适用于每个请求/响应,因为您添加了LoginRequiredMiddleware它将重定向到登录页面但您没有经过身份验证,因此您将再次被重定向到登录页面。 This url http://127.0.0.1:4050/login/?next=/login/ itself explains what is going on here.这个 url http://127.0.0.1:4050/login/?next=/login/本身解释了这里发生了什么。 You are accessing login page but you are redirected to login page again.您正在访问登录页面,但您再次被重定向到登录页面。

I think you are using this repo django-login-required-middleware , it is clearly mentioned that on their ReadMe我认为您正在使用此 repo django-login-required-middleware ,在他们的自述文件中明确提到

To ignore authentication in a view uses decorato @login_not_required for FBV or LoginNotRequiredMixin for CBV:要在视图中忽略身份验证,请使用装饰 @login_not_required 用于 FBV 或 LoginNotRequiredMixin 用于 CBV:

You need to change your LoginView to:您需要将LoginView更改为:

from login_required import LoginNotRequiredMixin
class LoginView(LoginNotRequiredMixin, CreateView):
"""
Login
"""
... // Rest of the code

You can also add list of url where LoginRequired should be ignored您还可以添加应忽略LoginRequired的 url 列表

LOGIN_REQUIRED_IGNORE_PATHS = [
    r'/accounts/logout/$'
    r'/accounts/signup/$',
    r'/admin/$',
    r'/admin/login/$',
    r'/about/$'
]

or Add LOGIN_REQUIRED_IGNORE_VIEW_NAMES setting.或添加LOGIN_REQUIRED_IGNORE_VIEW_NAMES设置。 Any requests which match these url name will be ignored.任何与这些 url 名称匹配的请求都将被忽略。 This setting should be a list filled with url names.此设置应该是一个列表,其中包含 url 名称。

LOGIN_REQUIRED_IGNORE_VIEW_NAMES = [
    'home',
    'login',
    'admin:index',
    'admin:login',
    'namespace:url_name',
]

It looks like for some reason you use the package django-login-required-middleware which provides a middleware so that login is required for all views.由于某种原因,您似乎使用了 package django-login-required-middleware ,它提供了一个中间件,因此所有视图都需要登录。 What is happening is that the middleware is assuming that even your login view requires the user to be logged in.正在发生的事情是中间件假设即使您的登录视图也需要用户登录。

You can stop this by using the LoginNotRequiredMixin (or login_not_required decorator for function based views) provided by the package (Reference django-login-required-middleware [GitHub] ):您可以使用 package 提供的LoginNotRequiredMixin (或基于 function 的视图的login_not_required装饰器)(参考django-login-required-middleware [GitHub] )来停止此操作:

from login_required import LoginNotRequiredMixin


class LoginView(LoginNotRequiredMixin, CreateView):
    # Your code here

Although this solves the issue do you even need to use this package?虽然这解决了这个问题,你甚至需要使用这个 package 吗? I would assume the The login_required decorator and the The LoginRequired mixin should normally be enough to assure users are logged in for views that need it to be that way.我会假设login_required 装饰器LoginRequired mixin通常应该足以确保用户登录到需要它的视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ERR_TOO_MANY_REDIRECTS 与 Django 中的中间件重定向 - ERR_TOO_MANY_REDIRECTS in redirect with middleware in Django 在 Django 中使用自定义中间件时出现“ERR_TOO_MANY_REDIRECTS”错误 - Getting 'ERR_TOO_MANY_REDIRECTS' error when using custom Middleware in Django 如何修复 ERR_TOO_MANY_REDIRECTS? - How to fix ERR_TOO_MANY_REDIRECTS? 尝试通过使用 Selenium 和 Python 的框架和 Javascript 的网页登录时出现 ERR_TOO_MANY_REDIRECTS 错误 - ERR_TOO_MANY_REDIRECTS error while trying to login through a webpage that uses frames and Javascript using Selenium and Python 无法将 jupyterhub 连接到 keycloak 并获得 ERR_TOO_MANY_REDIRECTS - Cant connect jupyterhub to keycloak and getting ERR_TOO_MANY_REDIRECTS Flask 应用程序中的 ERR_TOO_MANY_REDIRECTS。 在本地工作,但不在服务器中 - ERR_TOO_MANY_REDIRECTS in a Flask application. Works in local but not in server Heroku上的Django SSL重定向:“重定向过多” - Django SSL redirection on Heroku: 'Too many redirects' 使用Python请求重定向错误太多 - Too many redirects error using Python requests 使用中间件重定向到登录页面会导致“重定向过多”问题 - Redirect to login page with middleware is causing 'too many redirects" issue django-login-required-middleware WSGI 错误 - django-login-required-middleware WSGI error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM