在Django中调用用户关注/关注者列表

时间:2018-07-01 21:01:40

标签: django python-3.x django-models django-templates django-views

嗨,Djangonauts,                   我正在尝试在模板中获取用户关注列表(例如,Instagram的“ A”跟随“ B”之类的示例)。我已经尝试了几乎所有无法在模板中调用的内容。我在做什么错了

我的模型(这是Django用户模型的猴子补丁)

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))

我的观点(不确定是否正确)

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

我的模板

{{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 个答案:

答案 0 :(得分:1)

无效的位是循环,因为模板中未定义Contact。但是我不明白为什么您认为需要访问它。您应该遍历用户的“多对多”字段:

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