用户未在Models.py函数中定义

时间:2015-06-30 22:49:57

标签: python django

如何将其转换为可以从模板调用的函数?

>>> var1 = coremodels.Recommendation.objects.get(title="test5")
>>> user = User.objects.get(username='admin') // should get self.request.user
>>> var1.vote.exists(user)

当前尝试:

我目前在models.py中有它,但收到错误global name 'user' not defined

class Recommendation(models.Model):
    user = models.ForeignKey(User)
    def check_user_voted(self):
        user_voted = self.votes.exists(user)
        return user_voted

这是html请求:

{% if recommendation.check_user_voted %}
    <p>User Voted</p>
{% endif %}

2 个答案:

答案 0 :(得分:2)

只要您的函数不需要参数,就可以从模板调用它: https://docs.djangoproject.com/en/1.8/topics/templates/#variables

check_user_voted函数中,未定义user。它应该是:

def check_user_voted(self):
    user_voted = self.votes.exists(self.user)
    return user_voted

答案 1 :(得分:0)

要从模板调用函数,您需要使用装饰器@property

class Recommendation(models.Model):
    ...

    @property
    def check_user_voted(self):
        ....
        return something

然后从Recommendation对象中调用它:reco_object.check_user_voted

最后,要引用与当前recommendation对象关联的用户,您需要使用self.user,一旦User对象与关联对象关联,它将返回recommendation对象

def check_user_voted(self):
    user_voted = self.votes.exists(self.user)
    return user_voted