2013-03-16 111 views
0

我沒有解決這個問題的線索。Django - 如何從自定義模板標籤中檢索對象?

我已經接收的對象的模板標籤:

{% 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 %} 

我的問題。有可能從模板標籤中檢索一個對象?

最好的問候,

+0

你想唯一的比分在該標籤被通過? – catherine 2013-03-16 14:01:25

回答

2

要獲得得分:

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 %} 
相關問題