I use Django Templates as the template engine. Listing model has is_saved method which checks if the listing has been saved by the user.
listings\models.py:
class Listing(models.Model):
# ...
items = models.ManyToManyField(Item, blank=True)
saves = models.ManyToManyField("users.CustomUser", related_name="listing_saves", blank=True)
terms = models.ForeignKey(Terms, on_delete=models.CASCADE)
poster = models.ForeignKey("users.CustomUser", on_delete=models.CASCADE, db_column="poster_id")
class Meta:
db_table = "listing"
# ...
def is_saved(self, user):
return self.saves.filter(pk=user.pk).exists()
I am trying to call this method inside this template.
templates\partials\listings\list\footer.html:
{# Card footer #}
<div class="card-footer d-flex justify-content-between align-items-center">
{# ... #}
<form action="{% url 'listing-save' listing.id %}" method="post">
{# 4 CSRF tokens #}
{% csrf_token %}
<button class="btn btn-link" type="submit">
{% if listing.is_saved(user.id) %}
<i class="bi bi-bookmark-plus-fill text-success fs-4"></i>
{% else %}
<i class="bi bi-bookmark-plus text-success fs-4"></i>
{% endif %}
</button>
</form>
</div>
But this won’t work due to “security reasons” and I get this error:
TemplateSyntaxError at /oglasi/
Could not parse the remainder: '(user.id)' from 'listing.is_saved(user.id)'
So, I tried making a custom template tag as it’s been suggested online and loading it in the template:
listings\templatetags\listing_extras.py:
from django import template
register = template.Library()
@register.simple_tag
def call_method(obj, method_name, *args):
method = getattr(obj, method_name)
return method(*args)
templates\partials\listings\list\footer.html:
{% load listing_extras %}
{# Card footer #}
<div class="card-footer d-flex justify-content-between align-items-center">
{# ... #}
<form action="{% url 'listing-save' listing.id %}" method="post">
{# 4 CSRF tokens #}
{% csrf_token %}
<button class="btn btn-link" type="submit">
{% call_method is_saved listing user as var %}
{% if var %}
<i class="bi bi-bookmark-plus-fill text-success fs-4"></i>
{% else %}
<i class="bi bi-bookmark-plus text-success fs-4"></i>
{% endif %}
</button>
</form>
</div>
That didn’t work too.
TemplateSyntaxError at /oglasi/
'listing_extras' is not a registered tag library. Must be one of:
admin_list
admin_modify
admin_urls
auth
cache
i18n
l10n
log
static
tz