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, 3.4
- Supported django versions
- Django 1.2 - 1.8
An enhanced permission library which enables a logic-based permission system to handle complex permissions in Django.
It is developed based on the authentication backend system introduced in Django 1.2. This library does support Django 1.2 and higher.
Documentation¶
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
Autodiscovery¶
This is a new feature, added in django-permission 0.6.0, and the behavior was changed in django-permission 0.6.3.
Like django’s admin package, django-permission 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-permission 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)
Quick tutorial
Add
import permission; permission.autodiscover()
to yoururls.py
like:from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() # add this line import permission; permission.autodiscover() urlpatterns = patterns('', url(r'^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()), )
You can specify a different module or variable name, with PERMISSION_AUTODISCOVER_MODULE_NAME
or PERMISSION_AUTODISCOVER_VARIABLE_NAME
respectively.
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
From django-permission version 0.8.0, 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
)
# 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
#
# 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 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 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
From django-permission version 0.8.0, 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 http://django-permission.readthedocs.org/en/latest/_modules/permission/logics/collaborators.html#CollaboratorsPermissionLogic to learn how this logic works.
There are StaffPermissionLogic
and GroupInPermissionLogic
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.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
Override the builtin if
template tag¶
django-permission overrides the builtin if
tag, adding two operators to handle
permissions in templates.
You can write a permission test by using has
keyword, and a target object with of
as 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¶
Subpackages¶
permission.decorators package¶
Submodules¶
permission.decorators.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 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
>>> @permission_required('auth.change_user') >>> class UpdateAuthUserView(UpdateView): ... pass
permission.decorators.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 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
permission.decorators.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 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 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.decorators.permission_required module¶
-
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.
permission.decorators.utils module¶
Decorator utility module
Module contents¶
permission.logics package¶
Submodules¶
permission.logics.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 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 specified infield_name
of the object (e.g.obj.author
). So once user create an object and the object store who is the author infield_name
attribute (default:author
), the author can change or delete the object (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: boolean
Wheter the specified user have specified permission (of specified object).
permission.logics.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.
-
permission.logics.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 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: boolean
Wheter the specified user have specified permission (of specified object).
-
permission.logics.groupin module¶
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:
permission.logics.base.PermissionLogic
Permission logic class for group based permission system
Methods
-
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_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: boolean
Wheter the specified user have specified permission (of specified object).
-
permission.logics.oneself module¶
Permission logic module to manage users’ self-modifications
-
class
permission.logics.oneself.
OneselfPermissionLogic
(any_permission=None, change_permission=None, delete_permission=None)[source]¶ Bases:
permission.logics.base.PermissionLogic
Permission logic class to manage users’ self-modifications
Written by quasiyoke. https://github.com/lambdalisue/django-permission/pull/27
Methods
-
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: boolean
Wheter the specified user have specified permission (of specified object).
-
permission.logics.staff module¶
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:
permission.logics.base.PermissionLogic
Permission logic class for is_staff authority based permission system
Methods
-
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: boolean
Weather the specified user have specified permission (of specified object).
-
Module contents¶
Permission logic module
permission.templatetags package¶
Submodules¶
permission.templatetags.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
Module contents¶
permission.tests package¶
Subpackages¶
-
class
permission.tests.test_decorators.test_permission_required.
PermissionDecoratorsTestCase
(methodName='runTest')[source]¶ Bases:
django.test.testcases.TestCase
Attributes
available_apps fixtures Methods
Bases:
django.test.testcases.TestCase
Attributes
available_apps fixtures Methods
Bases:
django.test.testcases.TestCase
Attributes
available_apps fixtures Methods
Bases:
django.test.testcases.TestCase
Attributes
available_apps fixtures Methods
Submodules¶
permission.tests.compatibility module¶
permission.tests.models module¶
-
class
permission.tests.models.
Article
(id, title, content, author, editor, single_bridge, created_at)[source]¶ Bases:
django.db.models.base.Model
Attributes
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.
multiple_bridge
¶
-
Article.
objects
= <django.db.models.manager.Manager object>¶
-
Article.
single_bridge
¶
-
exception
-
class
permission.tests.models.
Bridge
(id, author)[source]¶ Bases:
django.db.models.base.Model
Attributes
Methods
-
exception
DoesNotExist
¶ Bases:
django.core.exceptions.ObjectDoesNotExist
-
exception
Bridge.
MultipleObjectsReturned
¶ Bases:
django.core.exceptions.MultipleObjectsReturned
-
Bridge.
editors
¶
-
Bridge.
objects
= <django.db.models.manager.Manager object>¶
-
Bridge.
permission_test_multiple_bridge
¶
-
Bridge.
permission_test_signgle_bridge
¶
-
exception
permission.tests.test_backends module¶
permission.tests.test_handlers module¶
-
class
permission.tests.test_handlers.
PermissionLogicalPermissionHandlerTestCase
(methodName='runTest')[source]¶ Bases:
django.test.testcases.TestCase
Attributes
available_apps fixtures Methods
permission.tests.utils module¶
Module contents¶
permission.utils package¶
Submodules¶
permission.utils.autodiscover module¶
-
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')
permission.utils.field_lookup module¶
-
permission.utils.field_lookup.
field_lookup
(obj, field_path)[source]¶ Lookup django model field in similar way of django query lookup
- Args:
- 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) >>> aritcle.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'))
permission.utils.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.
-
permission.utils.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 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)
permission.utils.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
Module contents¶
Submodules¶
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_module_perms
(user_obj, app_label)[source]¶ Check if user have permission of specified app based on registered handlers.
It will raise
ObjectDoesNotExist
exception when the specified string permission does not exist andPERMISSION_CHECK_PERMISSION_PRESENCE
isTrue
insettings
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
isTrue
insettings
module.
-
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 andPERMISSION_CHECK_PERMISSION_PRESENCE
isTrue
insettings
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
isTrue
insettings
module.
-
supports_anonymous_user
= True¶
-
supports_inactive_user
= True¶
-
supports_object_permissions
= True¶
-
permission.conf module¶
django-permission application configure
permission.handlers module¶
-
class
permission.handlers.
LogicalPermissionHandler
(model)[source]¶ Bases:
permission.handlers.PermissionHandler
Permission handler class which use permission logics to determine the permission
Attributes
Methods
-
has_perm
(user_obj, perm, obj=None)[source]¶ Check if user have permission (of object) based on specified models’s
_permission_logics
attribute.The result will be stored in user_obj as a cache to reduce method call.
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
Attributes
Methods
-
excludes
¶
-
get_supported_app_labels
()[source]¶ Get app labels which this handler can treat. Specified with
includes
andexcludes
of this instance.Returns: set
A set instance of app_label
-
get_supported_permissions
()[source]¶ Get permissions which this handler can treat. Specified with
includes
andexcludes
of this instance.Returns: set
A set instance of app_label.codename formatted permission strings
-
has_module_perms
(user_obj, app_label)[source]¶ Check if user have permission of specified app
Parameters: user_obj : django user model instance
A django user model instance which be checked
app_label : string
Django application name
Returns: boolean
Wheter the specified user have any permissions of specified app
-
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.
-
includes
¶
-
permission.models module¶
Module contents¶
django-permission