Django User Permissions on Jinja Template

  • Posted on: 7 September 2017
  • By: oon
Check Django User Permissions on Jinja2 Template

If you are using Django Template (DTL), you can easily get user permission in template (global) variable perms [1].

{% if perms.foo %}
    <p>You have permission to do something in the foo app.</p>
    {% if perms.foo.can_vote %}
        <p>You can vote!</p>
    {% endif %}
    {% if perms.foo.can_drive %}
        <p>You can drive!</p>
    {% endif %}
{% else %}
    <p>You don't have permission to do anything in the foo app.</p>
{% endif %}

What if we want to check permission on Jinja2 Template?

the easiest way, using user's method has_module_perms to check permission of current authenticated user to a module [1], let's convert from the sample above:

{% if request.user.has_module_perms('foo') %}

..snipped code..
{% endif %}

and as you may guess, the two-level-attribute lookup, using user's method has_perm to check permission for specific content type in a module [1].

{% if request.user.has_perm('foo.can_vote') %}
    <p>You can vote!</p>
{% endif %}

so, without any additional configuration on Jinja2 settings, you can check user permission on Jinja template.

if you want to look closely, take a look method PermWrapper on django.contrib.auth.context_processors [2].

[1]https://docs.djangoproject.com/en/stable/topics/auth/default/#permissions
[2]https://github.com/django/django/blob/master/django/contrib/auth/context...

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.