Calling user follow/follower list in Django

Multi tool use
Multi tool use


Calling user follow/follower list in Django



Hi Djangonauts,
I am trying to get the user follows list(example like Instagram 'A' follows 'B') in the templates. I have tried almost everything I am not able to call it in the templates. What am I doing wrong



My models (It's a monkey patch to the Django User model)


class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
#other profile fields


class Contact(models.Model):
user_from = models.ForeignKey(User, related_name='supporter')
user_to = models.ForeignKey(User, related_name='leader')

def __str__(self):
return '{} follows {}'.format(self.user_from, self.user_to)


User.add_to_class(
'following',
models.ManyToManyField(
'self',
through=Contact,
related_name='followers',
symmetrical=False))



My views (not sure if this is correct)


def get_context_data(self, **kwargs):
context = super(ProfileView, self).get_context_data(**kwargs)
context['follows'] = Contact.objects.filter(
user_from__isnull=False,
user_from__username__iexact=self.kwargs.get('username'))
context['followers'] = Contact.objects.filter(
user_to__isnull=False,
user_to__username__iexact=self.kwargs.get('username'))
return context



My Templates


{{user}} follows {{user.supporter.count}} members #This works shows the correct number
{% for contact in Contact.objects.all %}
{{contact.user_to.username}} # I am not able to get this part to work
{% endfor %}




1 Answer
1



The bit that isn't working is the loop, because Contact is not defined in the template. But I don't understand why you think you need to access it. You should be looping through the many-to-many field on the user:


Contact


{% for follow in user.following.all %}
{{ user.username }}
{% endfor %}





I don't even need the context in the views.py
– SamirTendulkar
Jul 1 at 21:20






No I don't think so.
– Daniel Roseman
Jul 1 at 21:21





I am sorry there is a small correction in your answer its {{ follow.username }}
– SamirTendulkar
Jul 1 at 22:18






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

uAxRt,g,c spSQXS2,QZMDg90d7nJrVHLd o527,olk8d405JyEgGxp5yBstgWyzO2thRmSjfkR0HxssvrB,CgNyD73kF8lR
K,9ruujyJOKzSkbq9zFUFmIV0zW4b7

Popular posts from this blog

Rothschild family

Cinema of Italy