Welcome to django-permission’s documentation!¶
django-permission¶







- Author
- Alisue <lambdalisue@hashnote.net>
- Supported python versions
- Python 2.6, 2.7, 3.2, 3.3
- Supported django versions
- Django 1.2 - 1.6
An enhanced permission library which enable logic based permission system to handle complex permissions in Django.
It is developed based on authentication backend system introduced from django 1.2. This library support Django 1.2 and later.
Documentation¶
Usage¶
Configuration¶
Put permission into your INSTALLED_APPS at settings module
INSTALLED_APPS = ( # ... 'permission', )
Add extra authorization backend
AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', # default 'permission.backends.PermissionBackend', )
Follow the instruction below to apply logical permissions to django models
Apply permission logic¶
Assume you have an article model which has author attribute to store who creat the article and you want to give the author full controll permissions (e.g. add, change, 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())
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 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
#
# You may 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 http://django-permission.readthedocs.org/en/latest/_modules/permission/logics/author.html#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 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)
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,
))
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 http://django-permission.readthedocs.org/en/latest/_modules/permission/logics/collaborators.html#CollaboratorsPermissionLogic to learn how this logic works.
Customize permission logic¶
Your own permission logic class must be a subclass of permission.logics.PermissionLogic and must override has_perm(user_obj, perm, obj=None) method which return boolean value.
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
Overwrite builtin if in template¶
django-permission overwrite builtin if tag to add two operator to handle permission in template. You can specify permission with has keyword and object with of keyword like the 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 %}
API documentation¶
permission Package¶
permission Package¶
django-permission
backends Module¶
Logical permission backends module
- class permission.backends.PermissionBackend[source]¶
Bases: object
A handler based permission backend
Methods
- authenticate(username, password)[source]¶
Always return None to prevent authentication within this backend.
- has_perm(user_obj, perm, obj=None)[source]¶
Check if user have permission (of object) based on registered handlers.
It will raise ObjectDoesNotExist exception when the specified string permission does not exist and PERMISSION_CHECK_PERMISSION_PRESENCE is True in settings module.
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 :
Wheter the specified user have specified permission (of specified object).
Raises: django.core.exceptions.ObjectDoesNotExist :
If the specified string permission does not exist and PERMISSION_CHECK_PERMISSION_PRESENCE is True in settings module.
- supports_anonymous_user = True¶
- supports_inactive_user = True¶
- supports_object_permissions = True¶
conf Module¶
django-permission application configure
handlers Module¶
- class permission.handlers.LogicalPermissionHandler(model)[source]¶
Bases: permission.handlers.PermissionHandler
Permission handler class which use permission logics to determine the permission
Methods
- has_perm(user_obj, perm, obj=None)[source]¶
Check if user have permission (of object) based on specified models’s _permission_logics attribute.
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 :
Wheter the specified user have specified permission (of specified object).
- class permission.handlers.PermissionHandler(model_or_app_label)[source]¶
Bases: object
Abstract permission handler class
Methods
- get_permissions(user_obj, perm, obj=None)[source]¶
Get permissions which this handler can treat. Specified with includes and excludes 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: set :
A set instance of app_label.codename formatted permission strings
- 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 :
Wheter the specified user have specified permission (of specified object).
.. note:: :
Sub class must override this method.
models Module¶
Subpackages¶
decorators Package¶
decorators Package¶
classbase Module¶
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: instance :
An instance of model object or None
- 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 use self 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 define get_queryset, queryset, get_object, or object then obj=None is used to check permission. With functional generic view, None for using passed queryset. When non queryset was passed then obj=None is used to check permission.
Examples
>>> @permission_required('auth.change_user') >>> class UpdateAuthUserView(UpdateView): ... pass
functionbase Module¶
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: instance :
An instance of model object or None
- 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: instance :
An instance of model object or None
- 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_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 define get_queryset, queryset, get_object, or object then obj=None is used to check permission. With functional generic view, None for using passed queryset. When non queryset was passed then obj=None is used to check permission.
Examples
>>> @permission_required('auth.change_user') >>> def update_auth_user(request, *args, **kwargs): ... pass
methodbase Module¶
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 use self 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 define get_queryset, queryset, get_object, or object then obj=None is used to check permission. With functional generic view, None for using passed queryset. When non queryset was passed then obj=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
logics Package¶
logics Package¶
Permission logic module
author Module¶
Permission logic module for author based permission system
Bases: permission.logics.base.PermissionLogic
Permission logic class for author based permission system
Methods
Check if user have permission (of object)
If no object is specified, it always return False so you need to add add permission to users in normal way.
If an object is specified, it will return True if the user is specified in field_name of the object (e.g. obj.author). So once user create an object and the object store who is the author in field_name attribute (default: author), the author can change or delete the object (you can change this behavior to set any_permission, change_permissino or delete_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: boolean :
Wheter the specified user have specified permission (of specified object).
base Module¶
- class permission.logics.base.PermissionLogic[source]¶
Bases: object
Abstract permission logic class
Methods
- 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 :
Wheter the specified user have specified permission (of specified object).
.. note:: :
Sub class must override this method.
collaborators Module¶
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: permission.logics.base.PermissionLogic
Permission logic class for collaborators based permission system
Methods
- has_perm(user_obj, perm, obj=None)[source]¶
Check if user have permission (of object)
If no object is specified, it always return False so you need to add add permission to users in normal way.
If an object is specified, it will return True if the user is found in field_name of the object (e.g. obj.collaborators). So once the object store the user as a collaborator in field_name attribute (default: collaborators), the collaborator can change or delete the object (you can change this behavior to set any_permission, change_permission or delete_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: boolean :
Wheter the specified user have specified permission (of specified object).
templatetags Package¶
permissionif Module¶
permissionif templatetag
Bases: django.template.smartif.IfParser
Permission if parser
Methods
use extra operator
Bases: permission.templatetags.permissionif.PermissionIfParser
Methods
alias of TemplateSyntaxError
Permission if templatetag
Examples
{% 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 %}
‘has’ operator of permission if
This operator is used to specify the user object of permission
‘of’ operator of permission if
This operator is used to specify the target object of permission
tests Package¶
tests Package¶
compatibility Module¶
models Module¶
- class permission.tests.models.Article(id, title, content, author_id, editor_id, created_at)[source]¶
Bases: django.db.models.base.Model
Methods
- exception DoesNotExist¶
Bases: django.core.exceptions.ObjectDoesNotExist
- exception Article.MultipleObjectsReturned¶
Bases: django.core.exceptions.MultipleObjectsReturned
- Article.editor¶
- Article.editors¶
- Article.get_next_by_created_at(*moreargs, **morekwargs)¶
- Article.get_previous_by_created_at(*moreargs, **morekwargs)¶
- Article.objects = <django.db.models.manager.Manager object at 0x4b2df10>¶
test_handlers Module¶
- class permission.tests.test_handlers.PermissionLogicalPermissionHandlerTestCase(methodName='runTest')[source]¶
Bases: django.test.testcases.TestCase
Attributes
Methods
utils Module¶
Subpackages¶
Bases: django.test.testcases.TestCase
Attributes
Methods
Bases: django.test.testcases.TestCase
Attributes
Methods
utils Package¶
handlers Module¶
A utilities of permission handler
- class permission.utils.handlers.PermissionHandlerRegistry[source]¶
Bases: object
A registry class of permission handler
Methods
- 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 or None
A permission handler class
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 Module¶
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 class
A permission logic class with 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
A permission logic class with 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 Module¶
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 perm (a string in format of ‘app_label.codename’) 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: set :
A set of perms of the specified django application.
Examples
>>> perms1 = get_app_perms('auth') >>> perms2 = get_app_perms(Permission) >>> perms1 == perms2 True
- permission.utils.permissions.get_model_perms(model)[source]¶
Get perm (a string in format of ‘app_label.codename’) list of the specified django model.
Parameters: model : model class
A model class to specify the particular django model.
Returns: set :
A set of perms of the specified django model.
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' True >>> get_perm_codename('app_label.codename') == 'codename' True >>> get_perm_codename('codename_model') == 'codename_model' True >>> get_perm_codename('codename') == 'codename' True >>> get_perm_codename('app_label.app_label.codename_model') == 'app_label.codename_model' True
- permission.utils.permissions.perm_to_permission(perm)[source]¶
Convert a identifier string permission format in ‘app_label.codename’ (teremd as perm) to a django permission instance.
Examples
>>> permission = perm_to_permission('auth.add_user') >>> permission.content_type.app_label == 'auth' True >>> permission.codename == 'add_user' True
- permission.utils.permissions.permission_to_perm(permission)[source]¶
Convert a django permission instance to a identifier string permission format in ‘app_label.codename’ (termed as perm).
Examples
>>> permission = Permission.objects.get( ... content_type__app_label='auth', ... codename='add_user', ... ) >>> permission_to_perm(permission) == 'auth.add_user' True