Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

django-guardian/django-guardian

Repository files navigation

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.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.