2014-03-04 206 views
0

我的觀點給我的列表或報告,而當前用戶呼叫方法

在我的模板我想做的事:

{% for report in reports %} 
    ... 
    {% if current_user.can_edit_report(report) == True %} 
     ... 
    {% endif %} 
    ... 
{% endfor %} 

但是罰球英里一個錯誤

Could not parse the remainder: '(report)' from 'current_user.can_edit_report(report)' 

因爲Django似乎無法使用模板中的參數調用方法。

所以,我必須這樣做在查看...

你有一個想法怎麼做是否正確?

由於

+0

也:http://stackoverflow.com/questions/1333189/django-template-system-calling -a-功能裏面,一個模型 – danihp

回答

1

是,如上文所註釋,這個問題有重複(How to call function that takes an argument in a Django template?)。

你想要做什麼是創建一個自定義模板標籤(https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags)是這樣的...

# template 
<p>Can Edit: {% can_edit_report user_id report_id %}.</p> 

# template_tags.py 
from django import template 

def can_edit_report(parser, token): 
    try: 
     # tag_name is 'can_edit_report' 
     tag_name, user_id, report_id = token.split_contents() 
     # business logic here (can user edit this report?) 
     user = User.objects.get(pk=user_id) 
     report = Report.objects.get(pk=report_id) 
     can_edit = user.can_edit_report(report) 
    except ValueError: 
     raise template.TemplateSyntaxError("%r tag requires two arguments" % token.contents.split()[0]) 
    return can_edit