23

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

MHS
  • 2,260
  • 11
  • 31
  • 45

1 Answers1

52

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 %}
Priyank Patel
  • 3,495
  • 20
  • 20
  • 6
    As of Django 1.9, you don't need to explicitly make an assignment tag. As of then, regular simple tags can be used in assignments: https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/#assignment-tags. – 8one6 Jun 23 '16 at 15:06
  • 1
    Still works in Django 3.2 with a simple tag. Updated documentation link: https://docs.djangoproject.com/en/3.2/howto/custom-template-tags/#setting-a-variable-in-the-context – JeremyM4n Jun 11 '21 at 18:22