Permissions (Django)

Permissions in Django control what an authenticated user is allowed to do. The framework auto-creates add/change/delete/view permissions per model, and you check them with user.has_perm() or the permission_required decorator.

Django

Where authentication answers 'who are you', permissions (authorization) answer 'what may you do'. Django generates four permissions for each model — add, change, delete, view — and you can define custom ones in a model's Meta.permissions for app-specific actions.

You assign permissions to users directly or, more commonly, group users (Group) and assign permissions to the group. In code you guard actions with request.user.has_perm('blog.change_post'), the @permission_required decorator on views, or PermissionRequiredMixin on class-based views; in templates use {{ perms.blog.change_post }}.

Superusers implicitly pass every permission check. For object-level permissions (this user may edit this specific post), the built-in system is model-level only, so projects add a library like django-guardian or check ownership manually in the view.

Syntax

user.has_perm("app.change_model")
@permission_required("app.add_post")

Examples

Python

from django.contrib.auth.decorators import permission_required

@permission_required("blog.add_post", raise_exception=True)
def create_post(request):
    ...

# in code
if request.user.has_perm("blog.delete_post"):
    post.delete()

Learn it in a lesson

See also

Back to the Dictionary