- Notifications
You must be signed in to change notification settings - Fork583
Per object permissions for Django
License
django-guardian/django-guardian
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
django-guardian is an implementation ofper-object permissions on topof Django’s authorization backend. Read an introduction to per-object permissionson djangoadvent articles.
Online documentation is available athttps://django-guardian.readthedocs.io/.
See real-world usage: Check outWho Uses Guardian to see how thousands of projects worldwide use django-guardian in production.
To installdjango-guardian into your project run:
uv add django-guardian
TIP: Not using a package manager like
uvorpoetryfor your django project? You probably should try them :). In the meantime,pip install django-guardianworks just fine too.
We need to hookdjango-guardian into our project.
- Put
guardianinto yourINSTALLED_APPSat settings module:
INSTALLED_APPS= ( ...'guardian',)
- Add extra authorization backend to your
settings.py:
AUTHENTICATION_BACKENDS= ('django.contrib.auth.backends.ModelBackend','guardian.backends.ObjectPermissionBackend',)
- Create
guardiandatabase tables by running:
python manage.py migrateAfter 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
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)
Users ofdjango-unfold will find thatguardian issupported out of the box via acontrib module.
About
Per object permissions for Django
Resources
License
Code of conduct
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Uh oh!
There was an error while loading.Please reload this page.