Check resolution inside a template in Django

Is it possible to use Auth application permission check inside a template in Django? (I want to show a simple form at the end of the template for privileged users)

And more importantly, should I do this at all or is this not a β€œDjango way”?

+64
django django-authentication
Feb 27 '12 at 17:44
source share
3 answers

If you want to check permissions in templates, the following code will suffice:

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

Where the model refers to the model that the user needs permissions to view the form for.

See https://docs.djangoproject.com/en/stable/topics/auth/default/#permissions for more details.

Currently existing user permissions are stored in the template variable {{ perms }}

(To do this, enable the following context processor: django.contrib.auth.context_processors.auth )

+152
Feb 28 2018-12-12T00:
source share

If you need more detail when checking perms (for example, for a specific object), check this extension: http://django-authority.readthedocs.org/en/latest/check_templates/

+2
Mar 08 '14 at 9:11
source share

Tested on Django 2.0+

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

 {{ perms.app_name }} 

Or

{{ perms }}

To check if a user has permission, use:

 {% if perms.app_name.change_model_name_lower_cased %} 

For example:

 {% if perms.Utilization.change_invoice %} 

Here: Use is the name of my application. Invoice is the name of the model.

Please note that in general there will be 4 types of permissions:

  • edit [For example, Utilization.change_projectemail]
  • view [For example, Utilization.view_invoice]
  • delete [eg Utilization.delete_invoicetype]
  • add [For example, Utilization.add_invoicetype]

Also, if you want to see all the permissions that the user has because of the groups to which he belongs, run the Django shell ...

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

Here, all of the listed permissions belong to the groups to which it belongs.

0
May 24 '19 at 11:39
source share



All Articles