Question

I do not see a clear distinction between using @login_required decorator and is_authenticated(): somehow, I think they perform similar checks (though not exactly).

Let say I have a function in my views.py:

def dosomethingNow(request):
     if request.user.is_authenticated():
         //carry out the function
     else:
          //redirect to login page

Same function with login_required decorator:

@login_required
def dosomethingNow(request):
     //carry out the function

Both the function does similar checks except that is_authenticated(), gives the option of redirecting to homepage if not logged in.

Any other benefits of using one over the other and places where they can't be used interchangeably?

Thanks

Was it helpful?

Solution

In the way you're using them in your example code, they're essentially equivalent.

Using user.is_aunthenticated is more flexible (as you note, you can decide what to do if they're not--output a different template, redirect to a login form, redirect somewhere else, etc.)

However, @login_required is "declarative", which can be nice. You could write a script that listed all of your view functions and whether or not they had the @login_required decorator around them, for instance, so you had a nice report of "login-required" sections of your site. When the checking happens in your own code buried inside the function, you lose that kind of possibility.

So it's a really a question of development style: do you need the flexibility to handle this as a special case? Or does make sense to use a declarative style?

(And, if you wanted a different implementation but a declarative style--say,if you frequently wanted to redirect non-logged-in-users to the homepage, you could write your own decorator, @homepage_if_not_auth, and use that)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top