我在实现比我的模板更大时遇到问题。我在首页上有一个用户喜欢的帖子,如果我的朋友喜欢一个帖子,我会在旁边显示我的朋友个人资料图片,例如count。现在,如果有10个朋友喜欢我的帖子,则我只希望五个朋友的个人资料图像显示在模板上,并且显示图像的末尾将显示“ +”。 “ +”表示还有更多朋友喜欢我的帖子。如果有更好的方法来实现视图,如何查询喜欢我帖子的朋友,您也可以提供帮助。我试过了但是没用;
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True)
profile_pic = models.ImageField(upload_to='ProfilePicture/', default="ProfilePicture/user-img.png", blank=True)
friends = models.ManyToManyField('Profile', related_name="my_friends",blank=True)
class Post(models.Model):
poster_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, blank=True,null=True)
likes = models.ManyToManyField('Profile', related_name='image_likes', blank=True)
def home(request):
#all post in homepage
posts = Post.objects.filter(poster_profile=request.user)
#Show friend who liked Post
friends_like_img = request.user.profile.friends.all().order_by('-id')
context = {'posts':posts,'friends_img':friends_img}
return render.....
{% for post in posts %}
{% for img in friends_like_img %}
{% if img in post.likes.all > 20 %}
<img src="{{ img.profile_pic.url }}" height="25" width="25" alt="profile_pic">
{% else %}
<img src="{{ img.profile_pic.url }}" height="25" width="25" alt="profile_pic"> +
{% endif %}
{% endfor %}
{% endfor %}
You need to use the
.count()
queryset method, and then compare to that.例:
您在上下文字典中名称不匹配。
更正为: