Check permission inside a template in Django

DjangoDjango Authentication

Django Problem Overview


Can I use the Auth application's permission checking inside a template in Django? (I want to display a simple form at the end of the template for privileged users)

And more importantly, should I do it at all or is this no the "Django way"?

Django Solutions


Solution 1 - Django

If you are looking to check for permissions in templates, the following code would suffice:

{% if perms.app_label.can_do_something %}
<form here>
{% endif %}

Where model refers to the model that the user need permissions to see the form for.

Refer to https://docs.djangoproject.com/en/stable/topics/auth/default/#permissions for more examples.

> The currently logged-in user's permissions are stored in the template variable {{ perms }}

(This requires the following context processor to be enabled: django.contrib.auth.context_processors.auth)

Solution 2 - Django

Tested on Django 2.0 +

If you want to see all the permissions the logged in user has, on your template (.html), print :

{{ perms.app_name }}

Or

{{ perms }}

In order to check if user has permission , use:

{% if perms.app_name.change_model_name_lower_cased %}

E.g :

{% if perms.Utilization.change_invoice %}

Here: Utilization is my App name. Invoice is a model name.

Note that in general, there will be 4 kinds of permissions:

  • change [E.g Utilization.change_projectemail]
  • view [E.g Utilization.view_invoice]
  • delete [E.g Utilization.delete_invoicetype]
  • add [E.g Utilization.add_invoicetype]

Also , if you want to see all permissions a user has due to the groups he belongs to, launch Django shell...

user = User.objects.get(username='somename')
user.get_group_permissions()

Here, all permissions listed, are due to the groups he belongs to.

Solution 3 - Django

If you need more granularity in checking perms (on a particular object for example), check out this extension: http://django-authority.readthedocs.org/en/latest/check_templates/

Solution 4 - Django

One more Unique way to do this is:

{% if 'app_label.permission' in perms %}
<form here>
{% endif %}

Example:

{% if 'auth.view_group' in perms %}
<p> Hello World! </p>
{% endif %}

This comes handy when you want to use your default/custom authentication permissions whether you've created an app for your model or not because this method don't need an app name. It just need the permission name from your permissions table.

You can put multiple checks also using and/or commands:

{% if 'auth.view_group' in perms and 'auth.add_group' in perms %}
<form here>
{% endif %}

Solution 5 - Django

And for those using Jinja templates and struggling with this question, like I did for a few hours/days...

  1. Use an extended Jinja Environment, and add the request object to it:
# in settings.py
TEMPLATES = [
    {
        "BACKEND": "django.template.backends.jinja2.Jinja2",
        'DIRS': ['jinja2'],
        "APP_DIRS": True,
        "OPTIONS": {
            'environment': 'main.jinjaconfig.env.environment',
        }
    },
    # Other template backends... 
]

# main/jinjaconfig/env.py
from django.template.context_processors import request
from jinja2 import Environment
# ...

def environment(**options):
    env = Environment(**options)
    # Update globals with the functions and objects you need, here 'request'
    env.globals.update({
        'request': request,
        # Other globals like 'static', 'url', ...
    })
    return env
  1. Then you can access the request object in Jinja templates, and also request.user and request.user.has_perm() and all user related functions:
{% if request.user.has_perm('app_label.can_do_something') %}
  {# Stuff .. #}
{% endif %}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanielView Question on Stackoverflow
Solution 1 - DjangoVictor NeoView Answer on Stackoverflow
Solution 2 - DjangoArindam RoychowdhuryView Answer on Stackoverflow
Solution 3 - DjangolaiView Answer on Stackoverflow
Solution 4 - DjangoAmar KumarView Answer on Stackoverflow
Solution 5 - DjangoscandelView Answer on Stackoverflow