In Django 2.0, I'm trying to call a method from a class, from a template.
Call from template
{% activity.liked_by(user) %}
Method from class
class Activity(models.Model):
name = models.CharField(max_length=15)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def liked_by(self, user):
return Like.objects.filter(activity_id=self.id, user_id=user.id)
I know this isn't possible, but what would be the best alternative? There's no way I can execute the query without passing user as an argument.
Thanks!
You can either provide the query in the context passed to the template or use a custom template tag. Lets assume the file that is created is called my_template_tags.py (note that this file must me in the correct directory structure).
from django import template
register = template.Library()
@register.simple_tag
def get_method(test, user):
return Test.objects.filter(test_id=test.id, user_id=user.id)
And then in the template:
{% load my_template_tags %}
{% get_method test user %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With