[英]How can I access a function from model in template in Django?
I have a model 'Post' and this has a function 'total_likes' that counts all the likes on a post. 我有一个模型“ Post”,它有一个函数“ total_likes”,该函数计算帖子中的所有点赞。 How can i access this function inside my template to show the number of likes? 如何在模板中访问此功能以显示喜欢的人数? Thank you! 谢谢!
Model: 模型:
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()
View: 视图:
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})
Template: 模板:
{% 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 %}
Just reference the method like any other attribute. 就像其他任何属性一样引用该方法。 Since it didn't take any parameters, Django will call it automatically. 由于它没有任何参数,因此Django会自动调用它。
{{ post.total_likes }}
就像您传递了{{post.id}}
,在呈现模板之前调用函数,并将arg传递给它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.