Search code examples
djangoauthenticationdjango-allauth

Why do Django have too many login redirects when using @login_required decorator?


I have searched for similar questions and answers for the question.I expect the home page to be displayed after authentication by a django-allauth view.But why do i have too many login redirects when using @login_required decorator?" Can you please explain the cause and the solution for the redirect loop? The code for the redirect loop is HTTP/1.1'' 302.

I looked up from the Django documentation that

@login_required decorator does the following:

  • If the user isn’t logged in, redirect to /accounts/login/, passing the current absolute URL in the query string as next, for example:/accounts/login/?next=/polls/3/.
  • If the user is logged in, execute the view normally. The view code can then assume that the user is logged in.

I want authenticated users to proceed to home page, while redirecting not logged in users to accounts/login page.

Part of my settings.py :

LOGIN_URL='/accounts/login/'
LOGIN_REDIRECT_URL='/'

My views.py :

from django.shortcuts import render
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
# Create your views here.
@login_required
def home(request):
    context={}
    template='home.html'
    return render(request, template,context)

My urls.py :

from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url, include
from django.contrib import admin   
from profiles import views as profiles_views

urlpatterns=[
url(r'^admin/',admin.site.urls),
url(r'$',profiles_views.home,name='home'),
url(r'^accounts/',include('allauth.urls')),

Solution

  • The problem is in your urls.py.

    You didn't put the "^", which marks the beginning of the line.

    Try,

    urlpatterns=[
        url(r'^admin/',admin.site.urls),
        url(r'^$',profiles_views.home,name='home'),
        url(r'^accounts/',include('allauth.urls')),
    ]