0

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 %}
2
  • Can you post your full model? Commented Jun 30, 2015 at 22:55
  • @Gocht sure: pastebin.com/QqJqZv8E Though i think this should be in views.py (just unsure how to create the function) Commented Jun 30, 2015 at 22:58

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

4 Comments

It doesn't have to be a property to call it from a template. It will just be called without parameters: docs.djangoproject.com/en/1.8/topics/templates/#variables
In fact, using the @property tag suggests it is a very 'lightweight' function, and because this is a database call, isn't that lightweight. This is not a rule, just a convention.
That example is about sending data from views, I talk about call a function in template.
"If a variable resolves to a callable, the template system will call it with no arguments and use its result instead of the callable."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.