【问题标题】:Calling user follow/follower list in Django在 Django 中调用用户关注/关注者列表
【发布时间】:2018-12-10 03:21:58
【问题描述】:

嗨,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 %}

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 我什至不需要views.py中的上下文
    • 不,我不这么认为。
    • 很抱歉,您的回答中有一个小的更正,它是 {{ follow.username }}
    猜你喜欢
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 2012-07-20
    • 1970-01-01
    相关资源
    最近更新 更多