我有一个模型“ Post”,它有一个功能“ total_likes”,该函数可以计算帖子中的所有点赞。如何在模板中访问此功能以显示喜欢的人数?谢谢!
型号:
class Post(models.Model):
created_date = models.DateTimeField()
title = models.CharField(max_length=100)
profile_image = models.ImageField(upload_to='poze', blank=True, null=True)
text = models.CharField(max_length=1000, default='Nimic', blank=True)
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
likes=models.ManyToManyField(UserProfile,related_name='likes',blank=True )
def total_likes(self):
return self.likes.count()
查看:
class ShowPosts(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'mainPage.html'
def get(self, request):
posts = Post.objects.all()
serializer = PostSerializer(posts, many=True)
return Response({'posts': serializer.data})
模板:
{% extends 'base2.html' %}
{% load static %}
{% load rest_framework %}
{% load crispy_forms_tags %}
<form action="{% url 'like_post' %}" method="post">
{% csrf_token %}
<button type="submit" name="post_id" value="{{ post.id}}">Like {{"How can I access the 'total_likes' function ?'}}</button>
</form>
{% endfor %}
{% endblock %}
答案 0 :(得分:0)
就像其他任何属性一样引用该方法。由于它没有任何参数,因此Django会自动调用它。
{{ post.total_likes }}
答案 1 :(得分:-1)
就像您通过{{post.id}}
一样,在呈现模板之前调用该函数,然后将arg传递给它