【发布时间】: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