Reputation: 17876
here is my simple_tag code
@register.simple_tag
def has_right(request,groupname):
if permission(request,groupname):
return True
return False
This is what I am trying to do in template
{% if has_right request 'admin' %}
display admin link
{%endif%}
but it complains
Exception Value:
Unused 'request' at end of if expression.
Is there other way in django template to evaluate tag result?
Upvotes: 2
Views: 2573
Reputation: 1237
The reason why it isn't working the way you want it to is because the template processor sees the {% if %} tag and begins processing it as a {% if %} tag, which isn't what you wanted. It looks like you wanted a kind of complex expression, where it would evaluate the contents of the if and then use that for conditional processing.
I'm not too sure if this is what you mean to use, but I think the easier solution would be t use the built in permissions in Django. Each user object has permissions attached to them already and adding and removing new permissions is rather simple too. https://docs.djangoproject.com/en/dev/topics/auth/#permissions is the link that you will want to check out. So on there, you should set some permissions in either your models or on the fly in a view, and then on the template side, all you would have to do is say
# Note that perms is a shortcut. Its the same as saying user.has_perm('')
{% if perms.has_that_permission %}
BUT even cooler than that I suppose, is each user already has the is_staff and is_superuser. So if these aren't currently in use by your app, I see no harm in using the is_staff at least to give users permissions on your site. Make sure you don't give them superuser permissions though, since being superuser means that any call to user.has_perm() will return TRUE no matter what.
Upvotes: 0
Reputation: 876
You can use the assignment tag.
@register.assignment_tag(takes_context=True)
def has_right(context,groupname):
request = context['request']
if permission(request,groupname):
return True
return False
And in Template
{% has_right as right %}
{% if right request 'admin' %}
display admin link
{%endif%}
Upvotes: 0
Reputation: 599788
If you need to calculate a value, you don't want a tag, you want a filter.
@register.filter
def has_right(request,groupname):
...
{% if request|has_right:groupname %}
Upvotes: 15