我知道它非常基本,但我无法弄清楚如何解决我的问题。
我有这样的模型:
class Follow(models.Model):
followed = models.ForeignKey(User, related_name='followed')
follower = models.ForeignKey(User, related_name='followers')
我的观点:
def usersList(request):
users = User.objects.all()
return render(request, 'blog/membres.html', {'users': users})
这就是我想在模板中做的事情:
{% for user in users %}
{% if request.user in user.followers.all %}
I'm following you !
{% else %}
I'm not following you
{% endif %}
{% endfor %}
但它没有用。我想我必须做这样的事情:
{% for user in users %}
{% if user.followers.filter(follower=request.user) %}
I'm following you !
{% else %}
I'm not following you
{% endif %}
{% endfor %}
答案 0 :(得分:0)
您必须正确地将users
对象传递给模板...
def home(request):
users = User.objects.all()
return render(request, 'pages/test.html', {'users':users})
HTML逻辑是正确的,它将完美运作......
答案 1 :(得分:0)
所以我找到了绕过问题的方法。
我将此方法添加到我的关注模型中:
def getListFollowed(self, user):
relations = Follow.objects.filter(follower=user)
liste = []
for relation in relations:
liste.append(relation.followed.username)
return liste
我改变了我的观点:
def membres(request):
users = User.objects.all()
f = Follow()
relations = f.getListFollowed(request.user)
return render(request, 'blog/membres.html', locals())
我在模板中这样做了:
{% if user in relations %}
I'm not following you!
{% else %}
I'm following you !
{% endif %}
我希望能帮助其他能和我一样的人