Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django/Python: Calling a model/class function with an argument from Template

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!

like image 935
SJ19 Avatar asked Nov 25 '25 12:11

SJ19


1 Answers

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 %}
like image 114
Stuart Dines Avatar answered Nov 27 '25 00:11

Stuart Dines



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!