django-guardian (3.0.6)

Published 2025-08-28 23:48:00 +02:00 by eofredj

Installation

pip install --index-url  django-guardian

About this package

Per object permissions for Django

django-guardian

Tests PyPI version Python versions

django-guardian is an implementation of per-object permissions on top of Django’s authorization backend. Read an introduction to per-object permissions on djangoadvent articles.

Documentation

Online documentation is available at https://django-guardian.readthedocs.io/.

Installation

To install django-guardian into your project run:

uv add django-guardian

TIP: Not using a package manager like uv or poetry for your django project? You probably should try them :). In the meantime, pip install django-guardian works just fine too.

Configuration

We need to hook django-guardian into our project.

  1. Put guardian into your INSTALLED_APPS at settings module:
INSTALLED_APPS = (
    ...
    'guardian',
)
  1. Add extra authorization backend to your settings.py:
AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'guardian.backends.ObjectPermissionBackend',
)
  1. Create guardian database tables by running:
python manage.py migrate

Usage

After installation and project hooks we can finally use object permissions with Django.

Lets start really quickly:

>>> from django.contrib.auth.models import User, Group
>>> jack = User.objects.create_user('jack', 'jack@example.com', 'topsecretagentjack')
>>> admins = Group.objects.create(name='admins')
>>> jack.has_perm('change_group', admins)
False
>>> from guardian.shortcuts import assign_perm
>>> assign_perm('change_group', jack, obj=admins)
<UserObjectPermission: admins | jack | change_group>
>>> jack.has_perm('change_group', admins)
True

Of course our agent jack here would not be able to change_group globally:

>>> jack.has_perm('change_group')
False

Admin integration

Replace admin.ModelAdmin with GuardedModelAdmin for those models which should have object permissions support within admin panel.

For example:

from django.contrib import admin
from myapp.models import Author
from guardian.admin import GuardedModelAdmin

# Old way:
#class AuthorAdmin(admin.ModelAdmin):
#    pass

# With object permissions support
class AuthorAdmin(GuardedModelAdmin):
    pass

admin.site.register(Author, AuthorAdmin)

Django Unfold integration

Users of django-unfold will find that guardian is supported out of the box via a contrib module.

Requirements

Requires Python: >=3.9
Details
PyPI
2025-08-28 23:48:00 +02:00
46
Chris Maggiuli, Bona Fide IT GmbH, Columbia University, SIS Development and Application Services
BSD-2-Clause
115 KiB
Assets (1)
Versions (3) View all
3.2.0 2025-10-26
3.0.6 2025-08-28
2.4.0 2024-11-27