0

Users that are not logged in are redirected by the @login_required()decorator to the LOGIN_URL specified in settings.py. So far so good. But I don't want that. Instead of redirecting them, I want to display an error message to those who are not logged in.

I thought this might work, but I get a TypeError: ios_login_required() takes exactly 1 argument (0 given) which I don't understand. It's a decorator, what argument does it need?

def ios_login_required(f):
    def wrapper(request, *args, **kwargs):
        if not request.user.is_authenticated:
            return HttpResponse("You need to be logged in.")
        else:
            return f(request, *args, **kwargs)
    return wrapper

The view with its decorator could look like this:

@ios_login_required()
def amiloggedinornot(request):
    return HttpResponse("Congrats, you are logged in!")

Any ideas where I went wrong?

okm
  • 23,575
  • 5
  • 83
  • 90
joschaf
  • 515
  • 2
  • 6
  • 14

1 Answers1

1
@ios_login_required()
def amiloggedinornot(request):
    ...

# equals to 
def amiloggedinornot(request):
    ...
amiloggedinornot = ios_login_required()(amiloggedinornot)

You could see that ios_login_required is invoked w/o any parameter whiles it needs a parameter f.

Thus try something like (without () after @ios_login_required):

@ios_login_required
def amiloggedinornot(request):
    ...

# which equals to
def amiloggedinornot(request):
    ...
amiloggedinornot = ios_login_required(amiloggedinornot)

You could read more about Python decorator here and here

Furthermore, user.is_authenticated is a method, you need to call it to get the boolean result. not user.is_authenticated will always be False.

Community
  • 1
  • 1
okm
  • 23,575
  • 5
  • 83
  • 90
  • When I omit the parentheses the return value is always ``"Congrats, you are logged in!"`` – joschaf Mar 09 '13 at 15:10
  • @Jo. The `TypeError` is fixed then. The `user.is_authenticated` is a method, it should be invoked: `if not request.user.is_authenticated():`. – okm Mar 09 '13 at 15:15
  • Right, I forgot to add the parentheses after ``is_authenticated``. Together with omitting the parentheses after ``@ios_login_required``it works as it should, thanks! But I'm curious, why do I need to omit them when I call this decorator? All my other decorators have them. Do you know? – joschaf Mar 09 '13 at 15:21
  • @Jo. Better to read Python decorator [here](http://stackoverflow.com/questions/739654/understanding-python-decorators) and [here](http://docs.python.org/2/reference/compound_stmts.html#function). The concept is simple: `@foo` above a function `bar` would replace the function w/ the result of `foo(bar)`, which is usually another function that has similar signature as the function `bar`; `@foo()` above a function `bar` would replace the function w/ the result of `foo()(bar)`. You could see their difference. I dont know how your other decorators looks like, but the rule is same. – okm Mar 09 '13 at 15:28