0

My view give me a list or reports and the current user

In my template I wanted to do :

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

But that throw mi a error

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

Because Django seems not to be able to call a method with parameter in a Template.

So I must do it in the View...

Do you have a idea how to do that properly?

Thanks

Yoann Augen
  • 1,966
  • 3
  • 21
  • 39

1 Answers1

3

Yes, as commented above, this question has duplicates (How to call function that takes an argument in a Django template?).

What you want to do is create a custom template tag (https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags) like so...

# 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
Community
  • 1
  • 1
Jeff Miller
  • 588
  • 1
  • 3
  • 13