Question

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?

Was it helpful?

Solution

@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.

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