【问题标题】:Django - How to retrieve an object from a custom template tag?Django - 如何从自定义模板标签中检索对象?
【发布时间】:2013-03-16 13:44:38
【问题描述】:

我没有解决这个问题的线索。

我有一个接收对象的模板标签:

{% score_for_object OBJECT_HERE as score2 %}

问题是我将来自原始选择的上下文传递给模板:

cursor = connection.cursor()
cursor.execute("select ...") 
comments = utils.dictfetchall(cursor)

为了解决模板标签接受Django对象的问题,我写了一个模板标签:

'''
This template tag is used to transform a comment_id in an object to use in the django-voting app
'''
def retrive_comment_object(comment_id):
    from myapp.apps.comments.models import MPTTComment
    return MPTTComment.objects.get(id=comment_id)

有了这个模板标签,我希望它可以工作:

{% for item in comments %}
    {% score_for_object item.comment_id|retrieve_comment_object as score2 %}

    {{ score2.score }} {# expected to work, but not working #}
{% endfor %}

我的问题。是否可以从模板标签中检索对象?

最好的问候,

【问题讨论】:

  • 您是否只想在该标签中通过分数?

标签: django django-templates django-voting


【解决方案1】:

要获得分数:

from django import template
from myapp.apps.comments.models import MPTTComment

register = template.Library()

@register.simple_tag
def retrive_comment_object(comment_id):
    data = MPTTComment.objects.get(id=comment_id)
    return data.score


{% for item in comments %}
    Score: {% retrive_comment_object item.comment_id %}
{% endfor %}

【讨论】:

    猜你喜欢
    • 2015-01-20
    • 2021-07-13
    • 1970-01-01
    • 2013-06-09
    • 2012-03-15
    • 1970-01-01
    • 2010-12-13
    • 2015-09-03
    相关资源
    最近更新 更多