Movatterモバイル変換


[0]ホーム

URL:


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

Sign up
Appearance settings

Per object permissions for Django

License

NotificationsYou must be signed in to change notification settings

django-guardian/django-guardian

Repository files navigation

TestsPyPI versionPython versionsPublished on Django Packages

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

Documentation

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

Installation

To installdjango-guardian into your project run:

uv add django-guardian

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

Configuration

We need to hookdjango-guardian into our project.

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

Usage

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

Lets start really quickly:

>>>fromdjango.contrib.auth.modelsimportUser,Group>>>jack=User.objects.create_user('jack','jack@example.com','topsecretagentjack')>>>admins=Group.objects.create(name='admins')>>>jack.has_perm('change_group',admins)False>>>fromguardian.shortcutsimportassign_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 tochange_group globally:

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

Admin integration

Replaceadmin.ModelAdmin withGuardedModelAdmin for those modelswhich should have object permissions support within admin panel.

For example:

fromdjango.contribimportadminfrommyapp.modelsimportAuthorfromguardian.adminimportGuardedModelAdmin# Old way:#class AuthorAdmin(admin.ModelAdmin):#    pass# With object permissions supportclassAuthorAdmin(GuardedModelAdmin):passadmin.site.register(Author,AuthorAdmin)

Django Unfold integration

Users ofdjango-unfold will find thatguardian issupported out of the box via acontrib module.


[8]ページ先頭

©2009-2025 Movatter.jp