k107
k107

Reputation: 16440

Django query manytomanyfield in template

How can I query a manytomanyfield in a Django template?

For example, this if statement doesn't work (I know I can't call functions with arguments in Django templates), but this shows what I'd like to do:

template.html

{% for post in posts %}
    {% if post.likes.filter(user=user) %}
        You like this post
    {% else %}
        <a>Click here to like this post</a>
    {% endif %}
{% endfor %}

models.py

class User(Model):
    # fields

class Post(Model):
    likes = ManyToManyField(User)

Upvotes: 3

Views: 441

Answers (2)

almostflan
almostflan

Reputation: 640

In order to do what you are looking for, you could do the following:

{% for post in posts %}
    {% if user in post.likes.distinct %}
        You like this post
    {% else %}
        <a>Click here to like this post</a>
    {% endif %}
{% endfor %}

Alternatively, you could use Greg's approach. The advantage of his answer is that it would scale better when you get into very large datasets. This approach does not require you to write any custom filters.

Upvotes: 3

Greg
Greg

Reputation: 10352

It doesn't work because you appear to be writing python code in a template... you need to either run the loop in your view and pass a list of posts and their information to the template, or write a template filter that determines whether a certain user likes a post. For example:

from django import template

register = template.Library()

@register.filter
def is_liked_by(post, user):
    return bool(post.likes.filter(user=user))

Then in your template:

{% for post in posts %}
    {% if post|is_liked_by:request.user %}
        You like this post
    {% else %}
        <a>Click here to like this post</a>
    {% endif %}
{% endfor %}

Upvotes: 4

Related Questions