【问题标题】:How can I access a function from model in template in Django?如何从 Django 模板中的模型访问函数?
【发布时间】:2018-08-12 23:15:51
【问题描述】:

我有一个模型“帖子”,它有一个函数“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 %}

【问题讨论】:

    标签: python django-rest-framework


    【解决方案1】:

    只需像引用任何其他属性一样引用该方法。由于它没有带任何参数,Django会自动调用它。

    {{ post.total_likes }}
    

    【讨论】:

      【解决方案2】:

      就像你传递{{post.id}}一样,在渲染模板之前调用函数,并将arg传递给它

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-23
        • 1970-01-01
        • 2014-08-20
        • 2014-08-01
        • 2015-03-17
        • 2013-03-16
        • 1970-01-01
        相关资源
        最近更新 更多