django-permission2
- Author
Malte Gerth <mail@malte-gerth.de>
- Original Author
Alisue <lambdalisue@hashnote.net>
- Supported python versions
Python 3.8, 3.9, 3.10, 3.11
- Supported django versions
Django 2.2, 3.2, 4.0, 4.1, 4.2
An enhanced permission library which enables a logic-based permission system to handle complex permissions in Django.
Documentation
Installation
Use pip like:
$ pip install django-permission2
Usage
The following might help you to understand as well.
Configuration
Add
permission
to theINSTALLED_APPS
in your settings moduleINSTALLED_APPS = ( # ... 'permission', )
Add our extra authorization/authentication backend
AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', # default 'permission.backends.PermissionBackend', )
Follow the instructions below to apply logical permissions to django models
Quick tutorial
Let’s assume you wrote an article model which has an author
attribute to store the creator of the article, and you want to give that author full control permissions
(e.g. add, change and delete permissions).
Add
import permission; permission.autodiscover()
to yoururls.py
like:from django.conf.urls import patterns, include from django.urls import path from django.contrib import admin admin.autodiscover() # only add the following line import permission; permission.autodiscover() urlpatterns = [ path('admin/', include(admin.site.urls)), # ... ]
Write
perms.py
in your application directory like:from permission.logics import AuthorPermissionLogic from permission.logics import CollaboratorsPermissionLogic PERMISSION_LOGICS = ( ('your_app.Article', AuthorPermissionLogic()), ('your_app.Article', CollaboratorsPermissionLogic()), )
What you need to do is just applying permission.logics.AuthorPermissionLogic
to the Article
model like
from django.db import models
from django.contrib.auth.models import User
class Article(models.Model):
title = models.CharField('title', max_length=120)
body = models.TextField('body')
author = models.ForeignKey(User)
# this is just required for easy explanation
class Meta:
app_label='permission'
# apply AuthorPermissionLogic
from permission import add_permission_logic
from permission.logics import AuthorPermissionLogic
add_permission_logic(Article, AuthorPermissionLogic())
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.
from permission.utils.permissions import perm_to_permission
user1.user_permissions.add(perm_to_permission('permission.add_article'))
assert user1.has_perm('permission.add_article') == True
assert user1.has_perm('permission.change_article') == False
assert user1.has_perm('permission.change_article', art1) == True
assert user1.has_perm('permission.change_article', art2) == False
assert user2.has_perm('permission.add_article') == False
assert user2.has_perm('permission.delete_article') == False
assert user2.has_perm('permission.delete_article', art1) == False
assert user2.has_perm('permission.delete_article', art2) == True
License
The MIT License (MIT)
Copyright (c) 2022 Malte Gerth <mail@malte-gerth.de>
Permission 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.
Installation
Installing django-permission2
Install latest stable version into your python environment using pip:
pip install django-permission2
Once installed add
permission
to yourINSTALLED_APPS
in settings.py:.. code:: python INSTALLED_APPS = ( ... 'permission', )
Add our extra authorization/authentication backend
AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', # default 'permission.backends.PermissionBackend', )
Follow the instructions below to apply logical permissions to django models
Autodiscovery
Like django’s admin package, django-permission2 automatically discovers the perms.py
in your application directory by running ``permission.autodiscover()``.
Additionally, if the perms.py
module has a PERMISSION_LOGICS
variable, django-permission2 automatically run the following functions to apply the permission logics.
for model, permission_logic_instance in PERMISSION_LOGICS:
if isinstance(model, str):
model = get_model(*model.split(".", 1))
add_permission_logic(model, permission_logic_instance)
Note
Autodiscover feature is automatically called. To disable, use PERMISSION_AUTODISCOVER_ENABLE setting.
Permissions
Apply permission logic
Let’s assume you wrote an article model which has an author
attribute 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 applying permission.logics.AuthorPermissionLogic
to the Article
model like
from django.db import models
from django.contrib.auth.models import User
class Article(models.Model):
title = models.CharField('title', max_length=120)
body = models.TextField('body')
author = models.ForeignKey(User)
# this is just required for easy explanation
class Meta:
app_label='permission'
# apply AuthorPermissionLogic
from permission import add_permission_logic
from permission.logics import AuthorPermissionLogic
add_permission_logic(Article, AuthorPermissionLogic())
Note
You can specify related object with field__name attribute like django queryset lookup. See the working example below:
from django.db import models
from django.contrib.auth.models import User
class Article(models.Model):
title = models.CharField('title', max_length=120)
body = models.TextField('body')
project = models.ForeignKey('permission.Project')
# this is just required for easy explanation
class Meta:
app_label='permission'
class Project(models.Model):
title = models.CharField('title', max_length=120)
body = models.TextField('body')
author = models.ForeignKey(User)
# this is just required for easy explanation
class Meta:
app_label='permission'
# apply AuthorPermissionLogic to Article
from permission import add_permission_logic
from permission.logics import AuthorPermissionLogic
add_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
)
# Grant the `permission.add_article` permission for user1.
# Use the `perm_to_permission` utility to convert the permission-string to a `Permission` object instance.
from permission.utils.permissions import perm_to_permission
user1.user_permissions.add(perm_to_permission('permission.add_article'))
# `add_article` is granted by user permissions
assert user1.has_perm('permission.add_article') == True
assert user2.has_perm('permission.add_article') == False
# `change_article` is not granted by user permissions
assert user1.has_perm('permission.change_article') == False
assert user2.has_perm('permission.change_article') == False
# `change_article` is granted by `AuthorPermissionLogic`
assert user1.has_perm('permission.change_article', art1) == True
# `change_article` is not granted by `AuthorPermissionLogic`
assert user1.has_perm('permission.change_article', art2) == False
# `delete_article` is not granted by user permissions
assert user1.has_perm('permission.delete_article') == False
assert user2.has_perm('permission.delete_article') == False
# `delete_article` is granted by `AuthorPermissionLogic`
assert user1.has_perm('permission.delete_article', art1) == True
# `delete_article` is not granted by `AuthorPermissionLogic`
assert user1.has_perm('permission.delete_article', art2) == False
# `delete_article` is not granted by `AuthorPermissionLogic`
assert user2.has_perm('permission.delete_article', art1) == False
# `delete_article` is granted by `AuthorPermissionLogic`
assert user2.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
#
from django.db.models.signals.post_save
from django.dispatch import receiver
from permission.utils.permissions import perm_to_permission
@receiver(post_save, sender=User)
def apply_permissions_to_new_user(sender, instance, created, **kwargs):
if not created:
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',
]
for permission in permissions:
# apply permission
# perm_to_permission is a utility to convert string permission
# to permission instance.
instance.user_permissions.add(perm_to_permission(permission))
See permission.logics.author.AuthorPermissionLogic
to learn how this logic works.
Now, assume you add collaborators
attribute to store collaborators
of the article and you want to give them a change permission.
What you need to do is quite simple.
Apply permission.logics.CollaboratorsPermissionLogic
to the Article
model as follows
from django.db import models
from django.contrib.auth.models import User
class Article(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 explanation
class Meta:
app_label='permission'
# apply AuthorPermissionLogic and CollaboratorsPermissionLogic
from permission import add_permission_logic
from permission.logics import AuthorPermissionLogic
from permission.logics import CollaboratorsPermissionLogic
add_permission_logic(Article, AuthorPermissionLogic())
add_permission_logic(Article, CollaboratorsPermissionLogic(
field_name='collaborators',
any_permission=False,
change_permission=True,
delete_permission=False,
))
Note
You can specify related object with field_name attribute like django queryset lookup. See the working example below:
from django.db import models
from django.contrib.auth.models import User
class Article(models.Model):
title = models.CharField('title', max_length=120)
body = models.TextField('body')
project = models.ForeignKey('permission.Project')
# this is just required for easy explanation
class Meta:
app_label='permission'
class Project(models.Model):
title = models.CharField('title', max_length=120)
body = models.TextField('body')
collaborators = models.ManyToManyField(User)
# this is just required for easy explanation
class Meta:
app_label='permission'
# apply AuthorPermissionLogic to Article
from permission import add_permission_logic
from permission.logics import CollaboratorsPermissionLogic
add_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)
assert user1.has_perm('permission.change_article') == False
assert user1.has_perm('permission.change_article', art1) == True
assert user1.has_perm('permission.delete_article', art1) == True
assert user2.has_perm('permission.change_article') == False
assert user2.has_perm('permission.change_article', art1) == True
assert user2.has_perm('permission.delete_article', art1) == False
See permission.logics.collaborators.CollaboratorsPermissionLogic
to learn how this logic works.
There are permission.logics.staff.StaffPermissionLogic
and
permission.logics.groupinGroupInPermissionLogic
for is_staff
or group
based permission logic as well.
Customize permission logic
Your own permission logic class must be a subclass of permission.logics.base.PermissionLogic
and must override
has_perm(user_obj, perm, obj=None)
method which return boolean value.
Decorators
Class, method, or function decorator
Like Django’s permission_required
but 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 use user.has_perm
in that case).
>>> from permission.decorators import permission_required
>>> # As class decorator
>>> @permission_required('auth.change_user')
>>> class UpdateAuthUserView(UpdateView):
... pass
>>> # As method decorator
>>> class UpdateAuthUserView(UpdateView):
... @permission_required('auth.change_user')
... def dispatch(self, request, *args, **kwargs):
... pass
>>> # As function decorator
>>> @permission_required('auth.change_user')
>>> def update_auth_user(request, *args, **kwargs):
... pass
License
The MIT License (MIT)
Copyright (c) 2022 Malte Gerth <mail@malte-gerth.de>
Permission 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.
Decorators
Class based
permission_required decorator for generic classbased view from django 1.3
- permission.decorators.classbase.get_object_from_classbased_instance(instance, queryset, request, *args, **kwargs)[source]
Get object from an instance of classbased generic view
- Parameters:
instance (instance) – An instance of classbased generic view
queryset (instance) – A queryset instance
request (instance) – A instance of HttpRequest
- Returns:
An instance of model object or None
- Return type:
instance
- permission.decorators.classbase.permission_required(perm, queryset=None, login_url=None, raise_exception=False)[source]
Permission check decorator for classbased generic view
This decorator works as class decorator DO NOT use
method_decorator
or whatever while this decorator will useself
argument for method of classbased generic view.- Parameters:
perm (string) – A permission string
queryset (queryset or model) – A queryset or model for finding object. With classbased generic view,
None
for using view default queryset. When the view does not defineget_queryset
,queryset
,get_object
, orobject
thenobj=None
is used to check permission. With functional generic view,None
for using passed queryset. When non queryset was passed thenobj=None
is used to check permission.
Examples
>>> @permission_required('auth.change_user') >>> class UpdateAuthUserView(UpdateView): ... pass
Function based
permission_required decorator for generic function view
- permission.decorators.functionbase.get_object_from_date_based_view(request, *args, **kwargs)[source]
Get object from generic date_based.detail view
- Parameters:
request (instance) – An instance of HttpRequest
- Returns:
An instance of model object or None
- Return type:
instance
- permission.decorators.functionbase.get_object_from_list_detail_view(request, *args, **kwargs)[source]
Get object from generic list_detail.detail view
- Parameters:
request (instance) – An instance of HttpRequest
- Returns:
An instance of model object or None
- Return type:
instance
- permission.decorators.functionbase.permission_required(perm, queryset=None, login_url=None, raise_exception=False)[source]
Permission check decorator for function-base generic view
This decorator works as function decorator
- Parameters:
perm (string) – A permission string
queryset (queryset or model) – A queryset or model for finding object. With classbased generic view,
None
for using view default queryset. When the view does not defineget_queryset
,queryset
,get_object
, orobject
thenobj=None
is used to check permission. With functional generic view,None
for using passed queryset. When non queryset was passed thenobj=None
is used to check permission.
Examples
>>> @permission_required('auth.change_user') >>> def update_auth_user(request, *args, **kwargs): ... pass
Method based
permission_required decorator for generic classbased/functionbased view
- permission.decorators.methodbase.permission_required(perm, queryset=None, login_url=None, raise_exception=False)[source]
Permission check decorator for classbased/functionbased generic view
This decorator works as method or function decorator DO NOT use
method_decorator
or whatever while this decorator will useself
argument for method of classbased generic view.- Parameters:
perm (string) – A permission string
queryset (queryset or model) – A queryset or model for finding object. With classbased generic view,
None
for using view default queryset. When the view does not defineget_queryset
,queryset
,get_object
, orobject
thenobj=None
is used to check permission. With functional generic view,None
for using passed queryset. When non queryset was passed thenobj=None
is used to check permission.
Examples
>>> # As method decorator >>> class UpdateAuthUserView(UpdateView): >>> @permission_required('auth.change_user') >>> def dispatch(self, request, *args, **kwargs): ... pass >>> # As function decorator >>> @permission_required('auth.change_user') >>> def update_auth_user(request, *args, **kwargs): ... pass
permission_required
Decorator module for permission
- permission.decorators.permission_required.permission_required(perm, queryset_or_model=None, login_url=None, raise_exception=False)[source]
Permission check decorator for classbased/functional generic view
This decorator works as class, method or function decorator without any modification. DO NOT use
method_decorator
or whatever while this decorator will useself
argument for method of classbased generic view.- Parameters:
perm (string) – A permission string
queryset_or_model (queryset or model) – A queryset or model for finding object. With classbased generic view,
None
for using view default queryset. When the view does not defineget_queryset
,queryset
,get_object
, orobject
thenobj=None
is used to check permission. With functional generic view,None
for using passed queryset. When non queryset was passed thenobj=None
is used to check permission.
Examples
>>> # As class decorator >>> @permission_required('auth.change_user') >>> class UpdateAuthUserView(UpdateView): ... pass >>> # As method decorator >>> class UpdateAuthUserView(UpdateView): ... @permission_required('auth.change_user') ... def dispatch(self, request, *args, **kwargs): ... pass >>> # As function decorator >>> @permission_required('auth.change_user') >>> def update_auth_user(request, *args, **kwargs): ... pass
Note
Classbased generic view is recommended while you can regulate the queryset with
get_queryset()
method. Detecting object from passed kwargs may not work correctly.
Decorators utils
Decorator utility module
Logics
Base Logic
- class permission.logics.base.PermissionLogic[source]
Bases:
object
Abstract permission logic class
- has_perm(user_obj, perm, obj=None)[source]
Check if user have permission (of object)
- Parameters:
user_obj (django user model instance) – A django user model instance which be checked
perm (string) – app_label.codename formatted permission string
obj (None or django model instance) – None or django model instance for object permission
- Returns:
boolean – Whether the specified user have specified permission (of specified object).
.. note:: – Sub class must override this method.
Collaborators logic
Permission logic module for collaborators based permission system
- class permission.logics.collaborators.CollaboratorsPermissionLogic(field_name=None, any_permission=None, change_permission=None, delete_permission=None)[source]
Bases:
PermissionLogic
Permission logic class for collaborators based permission system
- has_perm(user_obj, perm, obj=None)[source]
Check if user have permission (of object)
If the user_obj is not authenticated, it return
False
.If no object is specified, it return
True
when the corresponding permission was specified toTrue
(changed from v0.7.0). This behavior is based on the django system. https://code.djangoproject.com/wiki/RowLevelPermissionsIf an object is specified, it will return
True
if the user is found infield_name
of the object (e.g.obj.collaborators
). So once the object store the user as a collaborator infield_name
attribute (default:collaborators
), the collaborator can change or delete the object (you can change this behavior to setany_permission
,change_permission
ordelete_permission
attributes of this instance).- Parameters:
user_obj (django user model instance) – A django user model instance which be checked
perm (string) – app_label.codename formatted permission string
obj (None or django model instance) – None or django model instance for object permission
- Returns:
Whether the specified user have specified permission (of specified object).
- Return type:
boolean
GrouIn logic
Permission logic module for group based permission system
- class permission.logics.groupin.GroupInPermissionLogic(group_names, any_permission=None, add_permission=None, change_permission=None, delete_permission=None)[source]
Bases:
PermissionLogic
Permission logic class for group based permission system
- has_perm(user_obj, perm, obj=None)[source]
Check if user have permission (of object)
If the user_obj is not authenticated, it return
False
.If no object is specified, it return
True
when the corresponding permission was specified toTrue
(changed from v0.7.0). This behavior is based on the django system. https://code.djangoproject.com/wiki/RowLevelPermissionsIf an object is specified, it will return
True
if the user is in group specified ingroup_names
of this instance. This permission logic is used mainly for group based role permission system. You can change this behavior to setany_permission
,add_permission
,change_permission
, ordelete_permission
attributes of this instance.- Parameters:
user_obj (django user model instance) – A django user model instance which be checked
perm (string) – app_label.codename formatted permission string
obj (None or django model instance) – None or django model instance for object permission
- Returns:
Whether the specified user have specified permission (of specified object).
- Return type:
boolean
Oneself logic
Permission logic module to manage users’ self-modifications
- class permission.logics.oneself.OneselfPermissionLogic(any_permission=None, change_permission=None, delete_permission=None)[source]
Bases:
PermissionLogic
Permission logic class to manage users’ self-modifications
Written by quasiyoke. https://github.com/lambdalisue/django-permission/pull/27
- has_perm(user_obj, perm, obj=None)[source]
Check if user have permission of himself
If the user_obj is not authenticated, it return
False
.If no object is specified, it return
True
when the corresponding permission was specified toTrue
(changed from v0.7.0). This behavior is based on the django system. https://code.djangoproject.com/wiki/RowLevelPermissionsIf an object is specified, it will return
True
if the object is the user. So users can change or delete themselves (you can change this behavior to setany_permission
,change_permissino
ordelete_permission
attributes of this instance).- Parameters:
user_obj (django user model instance) – A django user model instance which be checked
perm (string) – app_label.codename formatted permission string
obj (None or django model instance) – None or django model instance for object permission
- Returns:
Whether the specified user have specified permission (of specified object).
- Return type:
boolean
Staff logic
Permission logic module for author based permission system
- class permission.logics.staff.StaffPermissionLogic(any_permission=None, add_permission=None, change_permission=None, delete_permission=None)[source]
Bases:
PermissionLogic
Permission logic class for is_staff authority based permission system
- has_perm(user_obj, perm, obj=None)[source]
Check if user have permission (of object)
If the user_obj is not authenticated, it return
False
.If no object is specified, it return
True
when the corresponding permission was specified toTrue
(changed from v0.7.0). This behavior is based on the django system. https://code.djangoproject.com/wiki/RowLevelPermissionsIf an object is specified, it will return
True
if the user is staff. The staff can add, change or delete the object (you can change this behavior to setany_permission
,add_permission
,change_permission
, ordelete_permission
attributes of this instance).- Parameters:
user_obj (django user model instance) – A django user model instance which be checked
perm (string) – app_label.codename formatted permission string
obj (None or django model instance) – None or django model instance for object permission
- Returns:
Weather the specified user have specified permission (of specified object).
- Return type:
boolean
Utils
Autodiscover
- permission.utils.autodiscover.autodiscover(module_name=None)[source]
Autodiscover INSTALLED_APPS perms.py modules and fail silently when not present. This forces an import on them to register any permissions bits they may want.
- permission.utils.autodiscover.discover(app, module_name=None)[source]
Automatically apply the permission logics written in the specified module.
Examples
Assume if you have a
perms.py
inyour_app
as:from permission.logics import AuthorPermissionLogic PERMISSION_LOGICS = ( ('your_app.your_model', AuthorPermissionLogic), )
Use this method to apply the permission logics enumerated in
PERMISSION_LOGICS
variable like:>>> discover('your_app')
field_lookup
A module to lookup field of object.
- permission.utils.field_lookup.field_lookup(obj, field_path)[source]
Lookup django model field in similar way of django query lookup.
- Parameters:
obj (instance) – Django Model instance
field_path (str) – ‘__’ separated field path
Example
>>> from django.db import model >>> from django.contrib.auth.models import User >>> class Article(models.Model): >>> title = models.CharField('title', max_length=200) >>> author = models.ForeignKey(User, null=True, >>> related_name='permission_test_articles_author') >>> editors = models.ManyToManyField(User, >>> related_name='permission_test_articles_editors') >>> user = User.objects.create_user('test_user', 'password') >>> article = Article.objects.create(title='test_article', ... author=user) >>> article.editors.add(user) >>> assert 'test_article' == field_lookup(article, 'title') >>> assert 'test_user' == field_lookup(article, 'user__username') >>> assert ['test_user'] == list(field_lookup(article, ... 'editors__username'))
Handlers utils
A utilities of permission handler
- class permission.utils.handlers.PermissionHandlerRegistry[source]
Bases:
object
A registry class of permission handler
- get_handlers()[source]
Get registered handler instances
- Returns:
permission handler tuple
- Return type:
tuple
- register(model, handler=None)[source]
Register a permission handler to the model
- Parameters:
model (django model class) – A django model class
handler (permission handler class, string, or None) – A permission handler class or a dotted path
- Raises:
ImproperlyConfigured – Raise when the model is abstract model
KeyError – Raise when the model is already registered in registry The model cannot have more than one handler.
Logics utils
Permission logic utilities
- permission.utils.logics.add_permission_logic(model, permission_logic)[source]
Add permission logic to the model
- Parameters:
model (django model class) – A django model class which will be treated by the specified permission logic
permission_logic (permission logic instance) – A permission logic instance which will be used to determine permission of the model
Examples
>>> from django.db import models >>> from permission.logics import PermissionLogic >>> class Mock(models.Model): ... name = models.CharField('name', max_length=120) >>> add_permission_logic(Mock, PermissionLogic())
- permission.utils.logics.remove_permission_logic(model, permission_logic, fail_silently=True)[source]
Remove permission logic to the model
- Parameters:
model (django model class) – A django model class which will be treated by the specified permission logic
permission_logic (permission logic class or instance) – A permission logic class or instance which will be used to determine permission of the model
fail_silently (boolean) – If True then do not raise KeyError even the specified permission logic have not registered.
Examples
>>> from django.db import models >>> from permission.logics import PermissionLogic >>> class Mock(models.Model): ... name = models.CharField('name', max_length=120) >>> logic = PermissionLogic() >>> add_permission_logic(Mock, logic) >>> remove_permission_logic(Mock, logic)
Permissions utils
Permission utility module.
In this module, term perm indicate the identifier string permission written in ‘app_label.codename’ format.
- permission.utils.permissions.get_app_perms(model_or_app_label)[source]
Get permission-string list of the specified django application.
- Parameters:
model_or_app_label (model class or string) – A model class or app_label string to specify the particular django application.
- Returns:
A set of perms of the specified django application.
- Return type:
set
Examples
>>> perms1 = get_app_perms('auth') >>> perms2 = get_app_perms(Permission) >>> perms1 == perms2 True
- permission.utils.permissions.get_model_perms(model)[source]
Get permission-string list of a specified django model.
- Parameters:
model (model class) – A model class to specify the particular django model.
- Returns:
A set of perms of the specified django model.
- Return type:
set
Examples
>>> sorted(get_model_perms(Permission)) == [ ... 'auth.add_permission', ... 'auth.change_permission', ... 'auth.delete_permission' ... ] True
- permission.utils.permissions.get_perm_codename(perm, fail_silently=True)[source]
Get permission codename from permission-string.
Examples
>>> get_perm_codename('app_label.codename_model') 'codename_model' >>> get_perm_codename('app_label.codename') 'codename' >>> get_perm_codename('codename_model') 'codename_model' >>> get_perm_codename('codename') 'codename' >>> get_perm_codename('app_label.app_label.codename_model') 'app_label.codename_model'
Backends
PermissionBackend
A handler based permission backend
Handlers
PermissionHandler
Abstract permission handler class
LogicalPermissionHandler
Permission handler class which use permission logics to determine the permission
Conf
permission.conf module
django-permission2 application configure