Answer the question
In order to leave comments, you need to log in
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
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})
urlpatterns = [
path('login/', views.user_login, name='login'),
]
urlpatterns = [
path('admin/', admin.site.urls),
path('travel/', include(('travel.urls', 'travel'), namespace='travel')),
path('account/', include(('account.urls', 'account'), namespace='account'))
]
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question