Kit Sunde
Kit Sunde

Reputation: 37075

I'd like to query a model based on the current user, in a template

I have an issue where I have something like this:

class Thing(models.Model):
    def can_vote(self, user):
        if self.vote_set.filter(user=user).count() < 2:
            return True
        # (A pile of other conditions)

class SomeUser(models.Model):
    pass

class Vote(models.Model):
    user = models.ForeignKey(SomeUser)
    things = models.ForeignKey(Thing)

and I want to do this in a template:

{% if thing.can_vote %}
   {# Review stuff #}
{% endif %}

Depending on if the current user has voted less than the amount of times or not. The issue seem to be that Django doesn't allow you to pass parameters to the method. Is there a way for me to accomplish this neatly?

Upvotes: 1

Views: 96

Answers (1)

DrTyrsa
DrTyrsa

Reputation: 31951

You can use custom template tag or filter. If filter:

@register.filter
def can_vote_on(user, thing):
    if thing.vote_set.filter(user=user).count() < 2:
        return True
    # (A pile of other conditions)

In template:

{% if user|can_vote_on:thing %}
   {# Review stuff #}
{% endif %}

Upvotes: 4

Related Questions