Search code examples
pythondjangoauthenticationdjango-viewsdjango-project-architect

how to restrict pages in Django? if "@login required(login_url='login')" does not work


I'm working on this signup-login project in Django and i want to restrict home page.. but for some reason this code is not working for me.. can you tell me why? and is there any other way to restrict pages in Django? @login_required(login_url='login')

views.py

@login_required(login_url='login')
def index(request):
   all_members = {}
   return render(request, "HTML/index.html",{'Members': all_members})

Solution

  • You could do something like:

    if not request.user.is_authenticated: #if the user is not authenticated
        return HttpResponseRedirect(reverse("login")) #redirect to login page
    else:
        #code
    

    And in terms of your code, have you included:

    from django.contrib.auth.decorators import login_required