Reputation: 1191
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 %}
Upvotes: 1
Views: 822
Reputation: 599638
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:
{% for follow in user.following.all %}
{{ follow.username }}
{% endfor %}
Upvotes: 1