[Django]-Check if user is following user?

2πŸ‘

βœ…

The problem is user_profile.followers.all will return list of Following instances, not users. And so user in user_profile.followers.all will not work. You can check follower with this query:

user_profile.followers.filter(follower=self.request.user).exists()

Since you cannot use this query in template you can override get_context_data and put result into context:

class ProfileView(DetailView):
    model = User
    slug_field = 'username'
    template_name = 'oauth/profile.html'
    context_object_name = 'user_profile' 

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['is_follower'] =  self.object.followers.filter(follower=self.request.user).exists()
        return context 

Not in template use variable is_follower instead:

{% if is_follower %}

Leave a comment