本文整理匯總了Python中django.contrib.auth.models.Permission方法的典型用法代碼示例。如果您正苦於以下問題:Python models.Permission方法的具體用法?Python models.Permission怎麽用?Python models.Permission使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.contrib.auth.models
的用法示例。
在下文中一共展示了models.Permission方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: settings
# 需要導入模塊: from django.contrib.auth import models [as 別名]
# 或者: from django.contrib.auth.models import Permission [as 別名]
def settings(self):
if self.cached_settings:
return self.cached_settings
else:
from django.conf import settings
allowed_configurations = {
'CONTENT_TYPE_CLASS': ContentType,
'USER_CLASS': settings.AUTH_USER_MODEL,
'PERMISSION_CLASS': Permission,
'GROUP_CLASS': Group,
'INJECT_MODEL_ADMIN': False
}
river_settings = {}
for key, default in allowed_configurations.items():
river_settings[key] = getattr(settings, self.get_with_prefix(key), default)
river_settings['IS_MSSQL'] = connection.vendor == 'microsoft'
self.cached_settings = river_settings
return self.cached_settings
示例2: setUp
# 需要導入模塊: from django.contrib.auth import models [as 別名]
# 或者: from django.contrib.auth.models import Permission [as 別名]
def setUp(self):
super(ReadTestCase, self).setUp()
self.group = Group.objects.create(name='test_group')
self.group__permissions = list(Permission.objects.all()[:3])
self.group.permissions.add(*self.group__permissions)
self.user = User.objects.create_user('user')
self.user__permissions = list(Permission.objects.all()[3:6])
self.user.groups.add(self.group)
self.user.user_permissions.add(*self.user__permissions)
self.admin = User.objects.create_superuser('admin', 'admin@test.me',
'password')
self.t1__permission = (Permission.objects.order_by('?')
.select_related('content_type')[0])
self.t1 = Test.objects.create(
name='test1', owner=self.user,
date='1789-07-14', datetime='1789-07-14T16:43:27',
permission=self.t1__permission)
self.t2 = Test.objects.create(
name='test2', owner=self.admin, public=True,
date='1944-06-06', datetime='1944-06-06T06:35:00')
示例3: test_filtered_relation
# 需要導入模塊: from django.contrib.auth import models [as 別名]
# 或者: from django.contrib.auth.models import Permission [as 別名]
def test_filtered_relation(self):
from django.db.models import FilteredRelation
qs = TestChild.objects.annotate(
filtered_permissions=FilteredRelation(
'permissions', condition=Q(permissions__pk__gt=1)))
self.assert_tables(qs, TestChild)
self.assert_query_cached(qs)
values_qs = qs.values('filtered_permissions')
self.assert_tables(
values_qs, TestChild, TestChild.permissions.through, Permission)
self.assert_query_cached(values_qs)
filtered_qs = qs.filter(filtered_permissions__pk__gt=2)
self.assert_tables(
values_qs, TestChild, TestChild.permissions.through, Permission)
self.assert_query_cached(filtered_qs)
示例4: test_difference
# 需要導入模塊: from django.contrib.auth import models [as 別名]
# 或者: from django.contrib.auth.models import Permission [as 別名]
def test_difference(self):
qs = Test.objects.filter(pk__lt=5)
sub_qs = Test.objects.filter(permission__name__contains='a')
if self.is_sqlite:
qs = qs.order_by()
sub_qs = sub_qs.order_by()
qs = qs.difference(sub_qs)
self.assert_tables(qs, Test, Permission)
self.assert_query_cached(qs)
qs = Test.objects.all()
sub_qs = Permission.objects.all()
if self.is_sqlite:
qs = qs.order_by()
sub_qs = sub_qs.order_by()
qs = qs.difference(sub_qs)
self.assert_tables(qs, Test, Permission)
with self.assertRaises((ProgrammingError, OperationalError)):
self.assert_query_cached(qs)
示例5: _get_users_with_any_permission_codenames_filter
# 需要導入模塊: from django.contrib.auth import models [as 別名]
# 或者: from django.contrib.auth.models import Permission [as 別名]
def _get_users_with_any_permission_codenames_filter(self, permission_codenames):
"""
Given a list of permission codenames, return a filter expression which
will find all users which have any of those permissions - either
through group permissions, user permissions, or implicitly through
being a superuser.
"""
permissions = Permission.objects.filter(
content_type=self._content_type,
codename__in=permission_codenames
)
return (
Q(is_superuser=True)
| Q(user_permissions__in=permissions)
| Q(groups__permissions__in=permissions)
) & Q(is_active=True)
示例6: setUp
# 需要導入模塊: from django.contrib.auth import models [as 別名]
# 或者: from django.contrib.auth.models import Permission [as 別名]
def setUp(self):
self.TestGroup = get_default_group_ctype().model_class()
self.user = TestUser.objects.create(username='test1', email='test@test.com')
self.user2 = TestUser.objects.create(username='test2', email='test2@test.com')
self.user3 = TestUser.objects.create(username='test3', email='test3@test.com')
self.responsible_user = TestUser.objects.create_user(username='responsible')
self.permission = Permission.objects.create(
codename='test', content_type=get_user_ctype()
)
self.permission2 = Permission.objects.create(
codename='test2', content_type=get_user_ctype()
)
self.permission_key = get_user_ctype().app_label + '.test'
self.permission2_key = get_user_ctype().app_label + '.test2'
self.group = self.TestGroup.objects.create(
name='test_group'
)
self.group2 = self.TestGroup.objects.create(
name='test_group2'
)
self.group2.restrict()
self.group2.save()
self.HistoryOwnerToPermission = HistoryOwnerToPermission
self.HistoryGenericUserToGroup = HistoryGenericUserToGroup
示例7: __unicode__
# 需要導入模塊: from django.contrib.auth import models [as 別名]
# 或者: from django.contrib.auth.models import Permission [as 別名]
def __unicode__(self):
if self.object_id is None:
ctype = None
else:
ctype = self.content_type
result = "{app}.{model}.{pk} ".format(
app=self.owner_content_type.app_label,
model=self.owner_content_type.model,
pk=self.owner_object_id,
)
if self.object_id is not None: # real object not global permission
result += "- {app}.{model}.{pk}. ".format(
app=ctype.app_label if ctype else '',
model=ctype.model if ctype else '',
pk=self.object_id or '',
)
if self.roles:
result += "Roles {roles}. ".format(roles=self.roles)
result += "Permission {perm}".format(perm=self.permission.codename)
return result
示例8: _filter_anonymous_perms
# 需要導入模塊: from django.contrib.auth import models [as 別名]
# 或者: from django.contrib.auth.models import Permission [as 別名]
def _filter_anonymous_perms(self, unfiltered_set):
"""
Restrict a set of tuples in the format (user_id, permission_id) to
only those permissions that apply to the content_type of this object
and are listed in settings.ALLOWED_ANONYMOUS_PERMISSIONS.
"""
content_type = ContentType.objects.get_for_model(self)
# Translate settings.ALLOWED_ANONYMOUS_PERMISSIONS to primary keys
codenames = set()
for perm in settings.ALLOWED_ANONYMOUS_PERMISSIONS:
app_label, codename = perm_parse(perm)
if app_label == content_type.app_label:
codenames.add(codename)
allowed_permission_ids = Permission.objects.filter(
content_type_id=content_type.pk, codename__in=codenames
).values_list('pk', flat=True)
filtered_set = copy.copy(unfiltered_set)
for user_id, permission_id in unfiltered_set:
if user_id == settings.ANONYMOUS_USER_ID:
if permission_id not in allowed_permission_ids:
filtered_set.remove((user_id, permission_id))
return filtered_set
示例9: get_users_with_perms
# 需要導入模塊: from django.contrib.auth import models [as 別名]
# 或者: from django.contrib.auth.models import Permission [as 別名]
def get_users_with_perms(self, attach_perms=False):
""" Return a QuerySet of all users with any effective grant permission
on this object. If attach_perms=True, then return a dict with
users as the keys and lists of their permissions as the values. """
user_perm_ids = self._get_effective_perms()
if attach_perms:
user_perm_dict = {}
for user_id, perm_id in user_perm_ids:
perm_list = user_perm_dict.get(user_id, [])
perm_list.append(Permission.objects.get(pk=perm_id).codename)
user_perm_dict[user_id] = sorted(perm_list)
# Resolve user ids into actual user objects
user_perm_dict = {User.objects.get(pk=key): value for key, value
in user_perm_dict.items()}
return user_perm_dict
else:
# Use a set to avoid duplicate users
user_ids = {x[0] for x in user_perm_ids}
return User.objects.filter(pk__in=user_ids)
示例10: reset_group_permissions
# 需要導入模塊: from django.contrib.auth import models [as 別名]
# 或者: from django.contrib.auth.models import Permission [as 別名]
def reset_group_permissions(group_name, app_permissions=(), cms_permissions=(), sites=()):
"""
Initialize a Django auth group assigning a set of Django app permissions,
and global page permissions for django CMS.
:param group_name: Name of Django auth group to create or reset
:param app_permissions: list of Django auth Permission objects
:param cms_permissions: dictionary of django CMS permissions
:param sites: optional list of Django sites objects (None: all sites)
:return: the created or updated group model instance
"""
group, created = Group.objects.get_or_create(name=group_name)
group.permissions = permission_list(app_permissions)
group.save()
perms, created = GlobalPagePermission.objects.get_or_create(group=group)
for attrib, value in dict(cms_permissions).items():
setattr(perms, attrib, value)
perms.sites = sites
perms.save()
return group
示例11: remove_perm_from_user
# 需要導入模塊: from django.contrib.auth import models [as 別名]
# 或者: from django.contrib.auth.models import Permission [as 別名]
def remove_perm_from_user(user, perm):
"""Remove a permission from an user"""
if isinstance(perm, str):
try:
app_label, codename = perm.split('.')
except ValueError:
raise ValueError('%s is not valid. Should be in format app_label.perm_codename')
else:
if not app_label or not codename:
raise ValueError('Invalid app_label or codename')
get_permission = Permission.objects.get
user.user_permissions.remove(
get_permission(content_type__app_label=app_label, codename=codename))
elif isinstance(perm, Permission):
user.user_permissions.remove(perm)
else:
raise TypeError('perm should be an instance of either str or Permission')
示例12: test_default_permissions
# 需要導入模塊: from django.contrib.auth import models [as 別名]
# 或者: from django.contrib.auth.models import Permission [as 別名]
def test_default_permissions(self):
permission_content_type = ContentType.objects.get_by_natural_key('auth', 'permission')
Permission._meta.permissions = [
('my_custom_permission', 'Some permission'),
]
create_permissions(self.app_config, verbosity=0)
# view/add/change/delete permission by default + custom permission
self.assertEqual(Permission.objects.filter(
content_type=permission_content_type,
).count(), 5)
Permission.objects.filter(content_type=permission_content_type).delete()
Permission._meta.default_permissions = []
create_permissions(self.app_config, verbosity=0)
# custom permission only since default permissions is empty
self.assertEqual(Permission.objects.filter(
content_type=permission_content_type,
).count(), 1)
示例13: get_editable_permissions
# 需要導入模塊: from django.contrib.auth import models [as 別名]
# 或者: from django.contrib.auth.models import Permission [as 別名]
def get_editable_permissions(self):
"""
Return a queryset of Permission objects that can be assigned
The view has an attribute called `editable_permissions` but that
attribute only lists app names and permission codenames. We need to
turn that tuple of tuples into a queryset of permissions.
"""
# Dynamic generation of OR queries is based on code found at
# https://bradmontgomery.net/blog/adding-q-objects-in-django/
permission_filter = Q()
for permission in self.editable_permissions:
permission_filter.add(
Q(content_type__app_label=permission[0],
codename=permission[1]), Q.OR)
return Permission.objects.filter(
permission_filter)
示例14: get_permissions_queryset
# 需要導入模塊: from django.contrib.auth import models [as 別名]
# 或者: from django.contrib.auth.models import Permission [as 別名]
def get_permissions_queryset(self):
"""
Get the queryset to pre-fill the optional individual permission list
There are a significant number of possible permissions within every
django app. Most of these permissions are not necessary for the
operation of the app, so we never display more than the ones required.
However, due to the way that UpdateViews and Many-to-Many forms are
saved when a form with a many-to-many field is submitted all existing
relationships are cleared and replaced with those submitted.
If, by some chance, a user has an individual permission that is not
listed above, the easiest way to handle this is to simply append the
permission to the form in order to prevent data corruption.
"""
editable_permissions_queryset = self.get_editable_permissions()
existing_permissions_queryset = self.object.user_permissions.all()
return Permission.objects.filter(
Q(pk__in=editable_permissions_queryset.values('pk')) |
Q(pk__in=existing_permissions_queryset.values('pk'))
).order_by('content_type__app_label').select_related('content_type')
示例15: setUp
# 需要導入模塊: from django.contrib.auth import models [as 別名]
# 或者: from django.contrib.auth.models import Permission [as 別名]
def setUp(self):
"""Handy things."""
self.request_factory = RequestFactory()
# Add 2 permissions to the test, one valid and visible, one hidden
demo_content_type = ContentType.objects.create(
app_label='demo-app-label', model='DemoModel')
self.valid_permission = mommy.make(
Permission,
codename='viewable-permission',
name='Viewable Permission',
content_type=demo_content_type)
self.hidden_permission = mommy.make(
Permission,
codename='hidden-permission',
name='Hidden Permission',
content_type=demo_content_type)
# Create a view class that contains those permissions
self.view_class = views.UpdateUserPermissionView
self.view_class.editable_permissions = (
('demo-app-label', 'viewable-permission'),
)