代码之家  ›  专栏  ›  技术社区  ›  Samir Tendulkar

在Django中调用用户跟踪/跟踪列表

  •  0
  • Samir Tendulkar  · 技术社区  · 7 年前

    嗨,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 回复  |  直到 7 年前
        1
  •  1
  •   Community Mohan Dere    7 年前

    不起作用的是循环,因为 Contact 未在模板中定义。但我不明白你为什么认为你需要访问它。您应该在用户的多对多字段中循环:

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