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’d like to render a list of posts along with a “follow” or “unfollow” link so that the current user can decide whether to follow a given post. In a world where I could use arguments in Django templating, I’d 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 can’t do that. And I can’t make a zero-argument, template-callable method on any of these models, because they all need to know at least one other argument to answer the question whether a given PostFollow row exists in that table.
I’m happy to write a templating extension, but before I bring out the big guns, is this an appropriate case for doing so? Or is there a more Djangoesque solution?
Template filters are not big guns:
and then:
You can also put all logic in template filter, remove ‘post.is_followed_by’ method and use the filter instead of model method just like any other function, @register.filter decorator doesn’t harm the decorated function.