如何将其转换为可以从模板调用的函数?
>>> 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 %}
答案 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