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"?
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.
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.
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.
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With