Package: django-permission
AuthorAlisue <lambdalisue@hashnote.net>Supported python versionsPython 2.7, 3.3, 3.4, 3.5, 3.6Supported django versionsDjango 1.8 - 1.11bAn enhanced permission library which enables alogic-based permission systemto handle complex permissions in Django.Documentationhttp://django-permission.readthedocs.org/en/latest/InstallationUsepiplike:$ pip install django-permissionUsageThe following might help you to understand as well.Basic strategy or so on,Issue #28Advanced usage and examples,Issue #26ConfigurationAddpermissionto theINSTALLED_APPSin your settings
moduleINSTALLED_APPS=(# ...'permission',)Add our extra authorization/authentication backendAUTHENTICATION_BACKENDS=('django.contrib.auth.backends.ModelBackend',# default'permission.backends.PermissionBackend',)Follow the instructions below to apply logical permissions to django modelsAutodiscoveryLike django’s admin package, django-permission automatically discovers theperms.pyin your application directoryby running ``permission.autodiscover()``.
Additionally, if theperms.pymodule has aPERMISSION_LOGICSvariable, django-permission automatically run the following functions to apply the permission logics.formodel,permission_logic_instanceinPERMISSION_LOGICS:ifisinstance(model,str):model=get_model(*model.split(".",1))add_permission_logic(model,permission_logic_instance)NoteAutodiscover feature is automatically called if you are using django higher than 1.7 so no need to follow the tutorial below.
To disable, usePERMISSION_AUTODISCOVER_ENABLEsetting.Quick tutorialAddimport permission; permission.autodiscover()to yoururls.pylike:fromdjango.conf.urlsimportpatterns,include,urlfromdjango.contribimportadminadmin.autodiscover()# add this lineimportpermission;permission.autodiscover()urlpatterns=patterns('',url(r'^admin/',include(admin.site.urls)),# ...)Writeperms.pyin your application directory like:frompermission.logicsimportAuthorPermissionLogicfrompermission.logicsimportCollaboratorsPermissionLogicPERMISSION_LOGICS=(('your_app.Article',AuthorPermissionLogic()),('your_app.Article',CollaboratorsPermissionLogic()),)You can specify a different module or variable name, withPERMISSION_AUTODISCOVER_MODULE_NAMEorPERMISSION_AUTODISCOVER_VARIABLE_NAMErespectively.Apply permission logicLet’s assume you wrote an article model which has anauthorattribute to store the creator of the article, and you want to give that author full control permissions
(e.g. add, change and delete permissions).What you need to do is just applyingpermission.logics.AuthorPermissionLogicto theArticlemodel likefromdjango.dbimportmodelsfromdjango.contrib.auth.modelsimportUserclassArticle(models.Model):title=models.CharField('title',max_length=120)body=models.TextField('body')author=models.ForeignKey(User)# this is just required for easy explanationclassMeta:app_label='permission'# apply AuthorPermissionLogicfrompermissionimportadd_permission_logicfrompermission.logicsimportAuthorPermissionLogicadd_permission_logic(Article,AuthorPermissionLogic())NoteFrom django-permission version 0.8.0, you can specify related object withfield__nameattribute likedjango queryset lookup.
See the working example below:fromdjango.dbimportmodelsfromdjango.contrib.auth.modelsimportUserclassArticle(models.Model):title=models.CharField('title',max_length=120)body=models.TextField('body')project=models.ForeignKey('permission.Project')# this is just required for easy explanationclassMeta:app_label='permission'classProject(models.Model):title=models.CharField('title',max_length=120)body=models.TextField('body')author=models.ForeignKey(User)# this is just required for easy explanationclassMeta:app_label='permission'# apply AuthorPermissionLogic to Articlefrompermissionimportadd_permission_logicfrompermission.logicsimportAuthorPermissionLogicadd_permission_logic(Article,AuthorPermissionLogic(field_name='project__author',))That’s it.
Now the following codes will work as expected:user1=User.objects.create_user(username='john',email='john@test.com',password='password',)user2=User.objects.create_user(username='alice',email='alice@test.com',password='password',)art1=Article.objects.create(title="Article 1",body="foobar hogehoge",author=user1)art2=Article.objects.create(title="Article 2",body="foobar hogehoge",author=user2)# You have to apply 'permission.add_article' to users manually because it# is not an object permission.frompermission.utils.permissionsimportperm_to_permissionuser1.user_permissions.add(perm_to_permission('permission.add_article'))assertuser1.has_perm('permission.add_article')==Trueassertuser1.has_perm('permission.change_article')==Falseassertuser1.has_perm('permission.change_article',art1)==Trueassertuser1.has_perm('permission.change_article',art2)==Falseassertuser2.has_perm('permission.add_article')==Falseassertuser2.has_perm('permission.delete_article')==Falseassertuser2.has_perm('permission.delete_article',art1)==Falseassertuser2.has_perm('permission.delete_article',art2)==True## You may also be interested in django signals to apply 'add' permissions to the# newly created users.# https://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.post_save#fromdjango.db.models.signals.post_savefromdjango.dispatchimportreceiverfrompermission.utils.permissionsimportperm_to_permission@receiver(post_save,sender=User)defapply_permissions_to_new_user(sender,instance,created,**kwargs):ifnotcreated:return## permissions you want to apply to the newly created user# YOU SHOULD NOT APPLY PERMISSIONS EXCEPT PERMISSIONS FOR 'ADD'# in this way, the applied permissions are not object permission so# if you apply 'permission.change_article' then the user can change# any article object.#permissions=['permission.add_article',]forpermissioninpermissions:# apply permission# perm_to_permission is a utility to convert string permission# to permission instance.instance.user_permissions.add(perm_to_permission(permission))Seehttp://django-permission.readthedocs.org/en/latest/_modules/permission/logics/author.html#AuthorPermissionLogicto learn how this logic works.Now, assume you addcollaboratorsattribute to store collaborators
of the article and you want to give them a change permission.What you need to do is quite simple.
Applypermission.logics.CollaboratorsPermissionLogicto theArticlemodel as followsfromdjango.dbimportmodelsfromdjango.contrib.auth.modelsimportUserclassArticle(models.Model):title=models.CharField('title',max_length=120)body=models.TextField('body')author=models.ForeignKey(User)collaborators=models.ManyToManyField(User)# this is just required for easy explanationclassMeta:app_label='permission'# apply AuthorPermissionLogic and CollaboratorsPermissionLogicfrompermissionimportadd_permission_logicfrompermission.logicsimportAuthorPermissionLogicfrompermission.logicsimportCollaboratorsPermissionLogicadd_permission_logic(Article,AuthorPermissionLogic())add_permission_logic(Article,CollaboratorsPermissionLogic(field_name='collaborators',any_permission=False,change_permission=True,delete_permission=False,))NoteFrom django-permission version 0.8.0, you can specify related object withfield_nameattribute likedjango queryset lookup.
See the working example below:fromdjango.dbimportmodelsfromdjango.contrib.auth.modelsimportUserclassArticle(models.Model):title=models.CharField('title',max_length=120)body=models.TextField('body')project=models.ForeignKey('permission.Project')# this is just required for easy explanationclassMeta:app_label='permission'classProject(models.Model):title=models.CharField('title',max_length=120)body=models.TextField('body')collaborators=models.ManyToManyField(User)# this is just required for easy explanationclassMeta:app_label='permission'# apply AuthorPermissionLogic to Articlefrompermissionimportadd_permission_logicfrompermission.logicsimportCollaboratorsPermissionLogicadd_permission_logic(Article,CollaboratorsPermissionLogic(field_name='project__collaborators',))That’s it.
Now the following codes will work as expected:user1=User.objects.create_user(username='john',email='john@test.com',password='password',)user2=User.objects.create_user(username='alice',email='alice@test.com',password='password',)art1=Article.objects.create(title="Article 1",body="foobar hogehoge",author=user1)art1.collaborators.add(user2)assertuser1.has_perm('permission.change_article')==Falseassertuser1.has_perm('permission.change_article',art1)==Trueassertuser1.has_perm('permission.delete_article',art1)==Trueassertuser2.has_perm('permission.change_article')==Falseassertuser2.has_perm('permission.change_article',art1)==Trueassertuser2.has_perm('permission.delete_article',art1)==FalseSeehttp://django-permission.readthedocs.org/en/latest/_modules/permission/logics/collaborators.html#CollaboratorsPermissionLogicto learn how this logic works.There areStaffPermissionLogicandGroupInPermissionLogicforis_stafforgroupbased permission logic as well.Customize permission logicYour own permission logic class must be a subclass ofpermission.logics.PermissionLogicand must overridehas_perm(user_obj, perm, obj=None)method which return boolean value.Class, method, or function decoratorLike Django’spermission_requiredbut it can be used for object permissions
and as a class, method, or function decorator.
Also, you don’t need to specify a object to this decorator for object permission.
This decorator automatically determined the object from request
(so you cannnot use this decorator for non view class/method/function but you
anyway useuser.has_permin that case).>>>frompermission.decoratorsimportpermission_required>>># As class decorator>>>@permission_required('auth.change_user')>>>classUpdateAuthUserView(UpdateView):...pass>>># As method decorator>>>classUpdateAuthUserView(UpdateView):...@permission_required('auth.change_user')...defdispatch(self,request,*args,**kwargs):...pass>>># As function decorator>>>@permission_required('auth.change_user')>>>defupdate_auth_user(request,*args,**kwargs):...passOverride the builtiniftemplate tagdjango-permission overrides the builtiniftag, adding two operators to handle
permissions in templates.
You can write a permission test by usinghaskeyword, and a target object withofas below.{% if user has 'blogs.add_article' %}<p>This user have 'blogs.add_article' permission</p>{% elif user has 'blog.change_article' of object %}<p>This user have 'blogs.change_article' permission of {{object}}</p>{% endif %}

{# If you set 'PERMISSION_REPLACE_BUILTIN_IF = False' in settings #}
{% permission user has 'blogs.add_article' %}<p>This user have 'blogs.add_article' permission</p>{% elpermission user has 'blog.change_article' of object %}<p>This user have 'blogs.change_article' permission of {{object}}</p>{% endpermission %}NoteFrom Django 1.9, users require to add‘permission.templatetags.permissionif’to‘builtins’option manually.
See
-https://docs.djangoproject.com/en/1.9/releases/1.9/#django-template-base-add-to-builtins-is-removed-https://docs.djangoproject.com/en/1.9/topics/templates/#module-django.template.backends.djangoOr following example:TEMPLATES=[{'BACKEND':'django.template.backends.django.DjangoTemplates','OPTIONS':{'builtins':['permission.templatetags.permissionif'],},},]LicenseThe MIT License (MIT)Copyright (c) 2015 Alisue, hashnote.netPermission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.