Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check permission inside a template in Django

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"?

like image 961
Daniel Avatar asked Feb 27 '12 17:02

Daniel


People also ask

What does Django template contains?

Being a web framework, Django needs a convenient way to generate HTML dynamically. The most common approach relies on templates. A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted.

What is {% include %} in Django?

Usage: {% extends 'parent_template. html' %} . {% block %}{% endblock %}: This is used to define sections in your templates, so that if another template extends this one, it'll be able to replace whatever html code has been written inside of it.

How do I know if my Django user is superuser?

So to test whether current user is superuser you can: if user.is_active and user. is_superuser: ... You can use it in template or pass this to template as variable via context.


1 Answers

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)

like image 65
Victor Neo Avatar answered Oct 06 '22 09:10

Victor Neo