TAGS :Viewed: 12 - Published at: a few seconds ago

[ User not Defined in Models.py Function ]

How do I turn this into a function that can be called from a template?

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

Current Attempt:

I currently have it in models.py but getting error 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

This is the html request:

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

Answer 1


As long as your function doesn't need parameters, it can be called from templates: https://docs.djangoproject.com/en/1.8/topics/templates/#variables

In your check_user_voted function, user is not defined. It should be:

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

Answer 2


To call a function from template, you need to use the decorator @property

class Recommendation(models.Model):
    ...

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

Then you call it from a Recommendation object: reco_object.check_user_voted

Finally, to reference the user associated to the current recommendation object, you need to use self.user which will return the User object once the recommendation object has one associated.

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