AttributeError at /profile/chandan 'tuple' object has no attribute 'another_user'

Viewed 33

I am trying to get follower system to work but it just wont work

class Followers(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    another_user = models.ManyToManyField(User, related_name='another_user')

    def __str__(self):
        return self.user.name


    def profile(request, user_name):
        user_obj = User.objects.get(username=user_name)
session_user, create = User.objects.get(username=user_name)
    session_following, create = Followers.objects.get_or_create(user=session_user)
        following = Followers.objects.get_or_create(user=session_user.id)
        check_user_followers = Followers.objects.filter(another_user=user_obj)
    
        is_followed = False 
        if session_following.another_user.filter(username=user_name).exists() or following.another_user.filter(username=user_name).exists():
            is_followed=True
        else:
            is_followed=False
        param = {'user_obj': user_obj,'followers':check_user_followers, 'following': following,'is_followed':is_followed}
        if 'user' in request.session:
            return render(request, 'users/profile2.html', param)
        else:
            return redirect('index')

I am getting the error:

AttributeError at /profile/chandan
'tuple' object has no attribute 'another_user'
1 Answers

get_or_create(…) [Django-doc] returns a 2-tuple with as first item the object, and as second item a boolean that indicates if the object was created (True), or already in the database.

You can make use of iterable unpacking to set the boolean to a "throwaway" variable:

#                  ↓ throw away the second item of the 2-tuple
session_following, __ = Followers.objects.get_or_create(user=session_user)
following, __ = Followers.objects.get_or_create(user=session_user)
Related