Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 989
k107 Avatar asked Dec 11 '25 09:12

k107


1 Answers

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 %}
like image 84
Greg Avatar answered Dec 12 '25 21:12

Greg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!