Is it possible for a Django template to test the existence of a row in a table without writing a special tag / filter?

I have the following models:

class Post(models.Model):
    message = models.TextField()
    (etc.)

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    (etc.)

class PostFollow(models.Model):
    post = models.ForeignKey(Post, related_name='follower_set')
    follower = models.ForeignKey(UserProfile, related_name='follower_set')
    creation_date = models.DateTimeField(auto_now_add=True)
    an_arbitrary_score = models.IntegerField(default=0)
    (etc.)

    class Meta:
        unique_together = ('post', 'follower',)

In my template, I would like to display a list of messages along with a follow or unfollow link so that the current user can decide whether to follow the given message. In a world where I could use arguments in Django templates, I would do something like this:

{% for post in post_set %}
    <...stuff...>
    {% if post.user_is_following user %}unfollow{% else %}follow{% endif %}
    <...more stuff...>
{% endfor %}

However, I cannot do this. And I cannot make an argument method with a null argument that can be used for any of these models, because they all need to know at least one other argument in order to answer the question whether this PostFollow row exists in this table.

, , ? Djangoesque?

+3
1

:

# your_app/templatetags/following.py 

from django import template
register = template.Library()

@register.filter
def is_followed_by(post, user):
   return post.is_followed_by(user)  

:

{% load following %}
...
{% if post|is_followed_by:user %} ... {% endif %}

, post.is_followed_by , , @register.filter decorator .

+5

Source: https://habr.com/ru/post/1762349/


All Articles