Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - How to use custom template tag with 'if' and 'else' checks? [duplicate]

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

like image 517
MHS Avatar asked Mar 21 '14 10:03

MHS


1 Answers

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 %}
like image 131
Priyank Patel Avatar answered Nov 14 '22 05:11

Priyank Patel