我对解决这个问题毫无头绪。
我有一个接收对象的模板标记:
{% score_for_object OBJECT_HERE as score2 %}问题是我向模板传递了一个来自原始select的上下文:
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 %}我的问题。是否可以从模板标记中检索对象?
诚挚的问候,
发布于 2013-03-16 22:07:07
要获得分数:
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 %}https://stackoverflow.com/questions/15450003
复制相似问题