0
0
Djangoframework~5 mins

Template permission checks in Django

Choose your learning style9 modes available
Introduction

Template permission checks help control what users see based on what they are allowed to do. This keeps your app safe and user-friendly.

Show or hide buttons depending on user roles.
Display special content only to logged-in users with certain rights.
Prevent users from seeing links to pages they cannot access.
Customize navigation menus based on user permissions.
Control form fields visibility depending on user access.
Syntax
Django
{% if perms.app_label.permission_codename %}
  <!-- content for users with permission -->
{% else %}
  <!-- content for others -->
{% endif %}
Use perms to check permissions in templates.
The format is perms.app_label.permission_codename, matching your Django app and permission.
Examples
Shows the 'Add Post' button only if the user has permission to add posts in the blog app.
Django
{% if perms.blog.add_post %}
  <button>Add Post</button>
{% endif %}
Shows an edit link if the user can change products; otherwise, shows a message.
Django
{% if perms.shop.change_product %}
  <a href="/edit-product/">Edit Product</a>
{% else %}
  <p>You cannot edit products.</p>
{% endif %}
Displays a welcome message only if the user has permission to view profiles.
Django
{% if perms.accounts.view_profile %}
  <p>Welcome back, valued user!</p>
{% endif %}
Sample Program

This template shows secret data only if the user has the view_secret_data permission in the app application. Otherwise, it shows a polite message.

Django
{# templates/example.html #}
<html lang="en">
<head>
  <title>Permission Check Example</title>
</head>
<body>
  <h1>Dashboard</h1>
  {% if perms.app.view_secret_data %}
    <p>Secret data: The launch code is 1234.</p>
  {% else %}
    <p>You do not have permission to see the secret data.</p>
  {% endif %}
</body>
</html>
OutputSuccess
Important Notes

Make sure your views pass the request context to templates so perms works.

Permission codenames are usually lowercase and use underscores.

You can combine permission checks with other template logic for more control.

Summary

Use perms.app_label.permission_codename in templates to check user permissions.

This helps show or hide content based on what users are allowed to do.

Always test permission checks to keep your app secure and user-friendly.