| in blog | timonweb.com |
|---|---|
| original entry | Checking Current User Permissions in Django Templates |
When developing Django applications, we often need to control which parts of the UI are accessible based on user permissions. Luckily, Django provides a straightforward way to check user permissions directly in templates using the perms object.
perms Object in Django TemplatesDjango automatically injects a perms context variable into templates, allowing you to check if a user has specific permissions. The syntax follows this pattern:
{% if perms.app_label.permission_codename %}
<!-- Content visible only to users with this permission -->
{% endif %}
In my case, I needed to check whether I should display a Wagtail Admin link to the current user or not.
In Wagtail, admin access permission has the permission codename access_admin, and it belongs to the wagtailadmin app. Therefore, in my template, I did the following to achieve my goal:
<ul>
{% if perms.wagtailadmin.access_admin %}
<li>
<a href="{% url 'wagtailadmin_home' %}">
Admin panel
</a>
</li>
{% endif %}
</ul>
perms.wagtailadmin.access_admin checks if the current user has the access_admin permission for the wagtailadmin app.As you can see, Django, as always, has got your back, and its perms object provides an easy way to manage user access within templates. Thank you, Django!