Permissions & Groups
Control who can do what with permissions and groups.
Syntax
user.has_perm("app.action_model")Django creates four default permissions per model: add, change, delete and view. Assign them to users directly or bundle them into groups (roles) for easier management.
Check a permission with user.has_perm() in code or {% if perms.app.perm %} in templates.
Example
# Check a permission in a view
if request.user.has_perm("blog.change_post"):
...
# Assign a user to a group
from django.contrib.auth.models import Group
editors = Group.objects.get(name="Editors")
request.user.groups.add(editors)
# In a template:
# {% if perms.blog.add_post %}<a href="...">New</a>{% endif %}When to use it
- A developer checks user.has_perm('blog.change_post') before showing an edit button in a template.
- A team creates a custom permission in a model's Meta class to control access to a sensitive report.
- A developer assigns the 'Editor' group to staff users so they automatically get the correct set of permissions.
More examples
Check permission in a view
Raises a 403 PermissionDenied exception when the user lacks the required object permission.
from django.core.exceptions import PermissionDenied
def post_edit(request, pk):
if not request.user.has_perm("blog.change_post"):
raise PermissionDenied
post = get_object_or_404(Post, pk=pk)
...Check permission in template
Uses the 'perms' template variable to conditionally show action links based on permissions.
{% if perms.blog.change_post %}
<a href="{% url 'post-edit' post.pk %}">Edit</a>
{% endif %}
{% if perms.blog.delete_post %}
<a href="{% url 'post-delete' post.pk %}">Delete</a>
{% endif %}Custom permission on a model
Declares custom permissions in Meta that Django will add to the auth system via migrations.
class Post(models.Model):
title = models.CharField(max_length=250)
class Meta:
permissions = [
("can_publish", "Can publish posts"),
("can_feature", "Can feature posts on homepage"),
]
Discussion