Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template - dynamic variable name

Tags:

django

Good Afternoon,

How can I use a variable variable name in Django templates?

I have a custom auth system using context, has_perm checks to see if the user has access to the specified section.

deptauth is a variable with a restriction group name i.e SectionAdmin. I think has.perm is actually checking for 'deptauth' instead of the variable value SectionAdmin as I would like.

{%if has_perm.deptauth %}

How can I do that? has_perm.{{depauth}} or something along those lines?

EDIT - Updated code

{% with arg_value="authval" %}
{% lookup has_perm "admintest" %}
{% endwith %}

{%if has_perm.authval %}
window.location = './portal/tickets/admin/add/{{dept}}/'+val;   
{% else %}
window.location = './portal/tickets/add/{{dept}}/'+val; 
{%endif%}     

has_perm isn't an object.. it's in my context processor (permchecker):

class permchecker(object):

def __init__(self, request):
    self.request = request
    pass

def __getitem__(self, perm_name):
    return check_perm(self.request, perm_name)  
like image 776
user2355278 Avatar asked Jun 17 '13 13:06

user2355278


Video Answer


1 Answers

You're best off writing your own custom template tag for that. It's not difficult to do, and normal for this kind of situation.

I have not tested this, but something along these lines should work. Remember to handle errors properly!

def lookup(object, property):
    return getattr(object, property)()

register.simple_tag(lookup)

If you're trying to get a property rather than execute a method, remove those ().

and use it:

{% lookup has_perm "depauth" %}

Note that has_perm is a variable, and "depauth" is a string value. this will pass the string for lookup, i.e. get has_perm.depauth.

You can call it with a variable:

{% with arg_value="depauth_other_value" %}
    {% lookup has_perm arg_value %}
{% endwith %}

which means that the value of the variable will be used to look it up, i.e. has_perm.depauth_other_value'.

like image 70
Joe Avatar answered Sep 30 '22 11:09

Joe