Использование экземпляра модели в пользовательском теге шаблона

Как я могу получить текущую модель экземпляра в templatetag, например:

from django import template
from users.models import Product

register = template.Library()

@register.simple_tag(name='description_tag')
def description_tag():
    custom_description = Product.product_description
    return custom_description

с помощью этого a получить объект: <django.db.models.query_utils.DeferredAttribute

У меня нет идеи, как получить текущую модель экземпляра, есть какие-нибудь советы?

Вы должны передать объект (или id и получить объект), прежде чем попытаться получить значение поля.

@register.simple_tag(name='description_tag')
def description_tag(product):
    custom_description = product.product_description
    return custom_description

# or if you have only id of Product object
@register.simple_tag(name='description_tag')
def description_tag(id):
    custom_description = Product.objects.get(id=id).product_description
    return custom_description

и в шаблоне что-то вроде:

{% product|description_tag %}

# or
{% some_id|description_tag %}

Но чтобы быть более точным, вам нужно поделиться своей моделью.

Вернуться на верх