[Django]-Django: 'User' object has no attribute 'user'

15👍

You need to remove @login_required() decorator from the get_alertnum() function. The decorator assumes the first argument is a request object and is trying to access the user attribute.

Also you could simplify and speed up the function by:

def get_alertnum(user):
    return Alert.objects.filter(read=False, for_user=user).count()

Below is an explanation of the count method.

https://docs.djangoproject.com/en/dev/ref/models/querysets/#count

12👍

This error also pops up when you use @login_required decorator on class. For class decoration use @method_decorator(login_required). See more in the Class based views docs.

2👍

The @login_required decorator only works on functions whose first argument is a request. Your stack trace is because it tries to use the user object as if it were a request object, and it doesn’t work. (as the other answer points out, user objects don’t have a .user attribute)

Perhaps instead get_alertnum() could check user.is_authenticated() first, and return 0 if the user is not authenticated.

For example:

def get_alertnum(user):
    if not user.is_authenticated():
        return 0
    else:
        return Alerts.objects.filter(read=False, for_user=user).count()

Leave a comment