S
S
Sergey Tryapkin2020-09-08 20:54:03
Django
Sergey Tryapkin, 2020-09-08 20:54:03

How to fix django middleware infinite redirect?

Hello.
Initially, the task is to close the entire site from unauthorized users.
I'm trying to solve this writing my middleware, but I ran into an endless redirect when the condition is met.

The middleware class itself:

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

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        login_path = '/account/login/'

        response = self.get_response(request)

        if not request.user.is_authenticated and request.path != login_path:
            return HttpResponseRedirect(reverse('account:user_login'))

        # Code to be executed for each request/response after
        # the view is called.

        return response


The view itself:
def user_login(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            user = authenticate(username=cd['username'], password=cd['password'])
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponse('Authenticated successfully')
                else:
                    return HttpResponse('Disabled account')
            else:
                return HttpResponse('Invalid login')
    else:
        form = LoginForm()
    return render(request, 'account/login.html', {'form': form})


url from account
urlpatterns = [
    path('login/', views.user_login, name='login'),
]


and project urls
urlpatterns = [
    path('admin/', admin.site.urls),
    path('travel/', include(('travel.urls', 'travel'), namespace='travel')),
    path('account/', include(('account.urls', 'account'), namespace='account'))
]


The middleware itself is connected to the last one in settings.py

As a result: I get an endless loop (302 in the console), nothing is returned to the face (the site did not respond)

What am I doing wrong and where to dig further?)
Thanks in advance to everyone!)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-09-08
@bacon

Debugging, from the simplest - add prints and use them to display the values ​​\u200b\u200bthat participate in the condition, before using debuggers, the same built-in pdb
PS well, such a check should be done before the view call, and not after.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question