I have made a custom template tag for permissions using python:
register = template.Library()
@register.simple_tag
def get_user_perm(request, perm):
try:
obj = Profile.objects.get(user=request.user)
obj_perms = obj.permission_tags.all()
flag = False
for p in obj_perms:
if perm.lower() == p.codename.lower():
flag = True
return flag
return flag
except Exception as e:
return ""
Then I loaded and used this in my template like this:
{% load usr_perm %}
{% get_user_perm request "add_users" %}
Which in return prints True. Now I want to use it as a check if user has permission or not? How can I use this template tag with if
and else
conditions?
Currently I am using it like this:
{% if get_user_perm request "add_users" %}Can Add User{% else %} Permission Denied {% endif %}
Is there any way that I can tweak in template tag's code or any hint to use template tag in template.
N.B: Previously I was using Django's permissions like this {% if perms.profile.add_user %}
but due to some reasons I have to write my own template tag now!
Any help will be greatly appreciated! Thanks
You should use Assignment tags
:
register = template.Library()
@register.assignment_tag(takes_context=True)
def get_user_perm(context, perm):
try:
request = context['request']
obj = Profile.objects.get(user=request.user)
obj_perms = obj.permission_tags.all()
flag = False
for p in obj_perms:
if perm.lower() == p.codename.lower():
flag = True
return flag
return flag
except Exception as e:
return ""
And after loading tags in templates . use it like :
{% get_user_perm "add_users" as add_users_flag %}
## you can check like this
{% if add_users_flag %} {% else %} {% endif %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With