本文整理汇总了Python中django.contrib.auth.models.Permission.DoesNotExist方法的典型用法代码示例。如果您正苦于以下问题:Python Permission.DoesNotExist方法的具体用法?Python Permission.DoesNotExist怎么用?Python Permission.DoesNotExist使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.contrib.auth.models.Permission
的用法示例。
在下文中一共展示了Permission.DoesNotExist方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_light_admin_group
# 需要导入模块: from django.contrib.auth.models import Permission [as 别名]
# 或者: from django.contrib.auth.models.Permission import DoesNotExist [as 别名]
def create_light_admin_group():
try:
# If "Light Admins" already exists, migration causes
# django.db.transaction.TransactionManagementError
# without transaction.atomic().
with transaction.atomic():
light_admin_group = Group.objects.create(name='Light Admins')
except IntegrityError:
print('\nGroup with name "Light Admins" already exists. Skipping creation.')
return
try:
regular_users_perm = Permission.objects.get(codename='change_organization_regular_users')
view_user = Permission.objects.get(codename='view_user')
except Permission.DoesNotExist:
print('\nMissing permissions. Skipping creation.')
return
light_admin_group.permissions.set([regular_users_perm, view_user])
示例2: create_userena_profile
# 需要导入模块: from django.contrib.auth.models import Permission [as 别名]
# 或者: from django.contrib.auth.models.Permission import DoesNotExist [as 别名]
def create_userena_profile(self, user):
"""
Creates an :class:`UserenaSignup` instance for this user.
:param user:
Django :class:`User` instance.
:return: The newly created :class:`UserenaSignup` instance.
"""
if isinstance(user.username, str):
user.username = smart_str(user.username)
try:
profile = self.get(user=user)
except self.model.DoesNotExist:
profile = self.create(user=user, activation_key=generate_nonce())
return profile
示例3: reissue_activation
# 需要导入模块: from django.contrib.auth.models import Permission [as 别名]
# 或者: from django.contrib.auth.models.Permission import DoesNotExist [as 别名]
def reissue_activation(self, activation_key):
"""
Creates a new ``activation_key`` resetting activation timeframe when
users let the previous key expire.
:param activation_key:
String containing the secret nonce activation key.
"""
try:
userena = self.get(activation_key=activation_key)
except self.model.DoesNotExist:
return False
try:
userena.activation_key = generate_nonce()
userena.save(using=self._db)
userena.user.date_joined = get_datetime_now()
userena.user.save(using=self._db)
userena.send_activation_email()
return True
except Exception:
return False
示例4: check_expired_activation
# 需要导入模块: from django.contrib.auth.models import Permission [as 别名]
# 或者: from django.contrib.auth.models.Permission import DoesNotExist [as 别名]
def check_expired_activation(self, activation_key):
"""
Check if ``activation_key`` is still valid.
Raises a ``self.model.DoesNotExist`` exception if key is not present or
``activation_key`` is not a valid string
:param activation_key:
String containing the secret nonce for a valid activation.
:return:
True if the ket has expired, False if still valid.
"""
if NONCE_RE.search(activation_key):
userena = self.get(activation_key=activation_key)
return userena.activation_key_expired()
raise self.model.DoesNotExist
示例5: permissions_audit
# 需要导入模块: from django.contrib.auth.models import Permission [as 别名]
# 或者: from django.contrib.auth.models.Permission import DoesNotExist [as 别名]
def permissions_audit(request, app_label, model, codename):
logger.debug("permissions_audit called by user {} on {}:{}:{}".format(request.user, app_label, model, codename))
try:
perm = Permission.objects\
.prefetch_related('group_set', 'user_set', 'state_set',
'state_set__userprofile_set', 'group_set__user_set', 'state_set__userprofile_set__user')\
.get(content_type__app_label=app_label, content_type__model=model, codename=codename)
except Permission.DoesNotExist:
raise Http404
context = {'permission': {
'permission': perm,
'users': perm.user_set.all(),
'groups': perm.group_set.all(),
'states': perm.state_set.all(),
'group_users': [group.user_set.all() for group in perm.group_set.all()],
'state_users': [state.userprofile_set.all() for state in perm.state_set.all()],
}
}
return render(request, 'permissions_tool/audit.html', context=context)
示例6: forwards
# 需要导入模块: from django.contrib.auth.models import Permission [as 别名]
# 或者: from django.contrib.auth.models.Permission import DoesNotExist [as 别名]
def forwards(self, orm):
pass
# remove old permission label if migrated with old model metadata
try:
ct = ContentType.objects.get(model='xform', app_label='odk_logger')
Permission.objects.get(content_type=ct, codename='can_view').delete()
# add new permission label
perm, created = Permission.objects.get_or_create(content_type=ct, codename='view_xform', name='Can view associated data')
except (ContentType.DoesNotExist, Permission.DoesNotExist):
pass
示例7: get_object
# 需要导入模块: from django.contrib.auth.models import Permission [as 别名]
# 或者: from django.contrib.auth.models.Permission import DoesNotExist [as 别名]
def get_object(collection, experiment=None, channel=None):
""" Return the resource from the request
Args:
collection: Collection name from the request
experiment: Experiment name from the request
channel: Channel name
Returns:
Instance of the resource from the request
"""
try:
if collection and experiment and channel:
# Channel specified
collection_obj = Collection.objects.get(name=collection)
experiment_obj = Experiment.objects.get(name=experiment, collection=collection_obj)
obj = Channel.objects.get(name=channel, experiment=experiment_obj)
resource_type = 'channel'
elif collection and experiment:
# Experiment
collection_obj = Collection.objects.get(name=collection)
obj = Experiment.objects.get(name=experiment, collection=collection_obj)
resource_type = 'experiment'
elif collection:
obj = Collection.objects.get(name=collection)
resource_type = 'collection'
else:
return None
return (obj, resource_type)
except Collection.DoesNotExist:
raise BossError("{} does not exist".format(collection), ErrorCodes.RESOURCE_NOT_FOUND)
except Experiment.DoesNotExist:
raise BossError("{} does not exist".format(experiment), ErrorCodes.RESOURCE_NOT_FOUND)
except Channel.DoesNotExist:
raise BossError("{} does not exist".format(channel), ErrorCodes.RESOURCE_NOT_FOUND)
# @check_role("resource-manager")
示例8: get_permission_id_by_name
# 需要导入模块: from django.contrib.auth.models import Permission [as 别名]
# 或者: from django.contrib.auth.models.Permission import DoesNotExist [as 别名]
def get_permission_id_by_name(permission):
cache_key = 'permission_id_cache_' + permission
perm_id = cache.get(cache_key, None)
if perm_id is None:
try:
perm_id = Permission.objects.get(
codename=permission.split('.')[1],
content_type__app_label=permission.split('.')[0]
).id
except Permission.DoesNotExist:
return None
cache.set(cache_key, perm_id)
return perm_id
示例9: get_permissions
# 需要导入模块: from django.contrib.auth.models import Permission [as 别名]
# 或者: from django.contrib.auth.models.Permission import DoesNotExist [as 别名]
def get_permissions(names):
"""
Given an iterable of permission names of the form "app_label.codename",
return an iterable of the corresponding existing Permission objects.
"""
names = set(names) # Eliminate redundancies
split_names = (name.split(".", 1) for name in names)
query_elements = [
Q(content_type__app_label=app_label, codename=codename)
for app_label, codename in split_names
]
permissions = (
Permission.objects.filter(reduce(or_, query_elements))
if query_elements
else Permission.objects.none()
)
if len(permissions) != len(names):
differences = names - {
f"{p.content_type.app_label:s}.{p.codename:s}" for p in permissions
}
raise Permission.DoesNotExist(
"Some permission names were not found: {:s}".format(", ".join(differences))
)
return permissions
示例10: test_helpers_get_permissions_unknown
# 需要导入模块: from django.contrib.auth.models import Permission [as 别名]
# 或者: from django.contrib.auth.models.Permission import DoesNotExist [as 别名]
def test_helpers_get_permissions_unknown(self):
"""Trying to retrieve a permission that does not exist should raise an exception."""
with self.assertRaises(Permission.DoesNotExist) as context:
get_permissions(["unknown.unknown"])
self.assertEqual(
str(context.exception),
"Some permission names were not found: unknown.unknown",
)
示例11: get_permission_obj
# 需要导入模块: from django.contrib.auth.models import Permission [as 别名]
# 或者: from django.contrib.auth.models.Permission import DoesNotExist [as 别名]
def get_permission_obj(pid):
try:
return Permission.objects.get(pk=pid)
except Permission.DoesNotExist:
return None
示例12: has_list_permission
# 需要导入模块: from django.contrib.auth.models import Permission [as 别名]
# 或者: from django.contrib.auth.models.Permission import DoesNotExist [as 别名]
def has_list_permission(self, user):
try:
list_perm_codename = 'list_%s' % self.opts.model_name
perm = Permission.objects.get(
content_type__app_label=self.opts.app_label,
codename=list_perm_codename,
)
return user.has_perm(perm)
except Permission.DoesNotExist:
pass
return super(ReadOnlyPermissionHelper, self).has_list_permission(user)
示例13: handle
# 需要导入模块: from django.contrib.auth.models import Permission [as 别名]
# 或者: from django.contrib.auth.models.Permission import DoesNotExist [as 别名]
def handle(self, *args, **options):
# Loop groups
for group_name in GROUPS_PERMISSIONS:
# Get or create group
group, created = Group.objects.get_or_create(name=group_name)
if created:
self.stdout.write("Created group {}".format(group.__str__()))
# Loop models in group
for model_cls in GROUPS_PERMISSIONS[group_name]:
# Loop permissions in group/model
for perm_index, perm_name in enumerate(GROUPS_PERMISSIONS[group_name][model_cls]):
# Generate permission name as Django would generate it
codename = perm_name + "_" + model_cls._meta.model_name
try:
# Find permission object and add to group
perm = Permission.objects.get(codename=codename)
group.permissions.add(perm)
except Permission.DoesNotExist:
self.stdout.write("{} permission not found".format(codename))
示例14: activate_user
# 需要导入模块: from django.contrib.auth.models import Permission [as 别名]
# 或者: from django.contrib.auth.models.Permission import DoesNotExist [as 别名]
def activate_user(self, activation_key):
"""
Activate an :class:`User` by supplying a valid ``activation_key``.
If the key is valid and an user is found, activates the user and
return it. Also sends the ``activation_complete`` signal.
:param activation_key:
String containing the secret nonce for a valid activation.
:return:
The newly activated :class:`User` or ``False`` if not successful.
"""
if NONCE_RE.search(activation_key):
try:
userena = self.get(activation_key=activation_key)
except self.model.DoesNotExist:
return False
if not userena.activation_key_expired():
userena.activation_key = userena_settings.USERENA_ACTIVATED
user = userena.user
user.is_active = True
userena.save(using=self._db)
user.save(using=self._db)
# Send the activation_complete signal
userena_signals.activation_complete.send(sender=None, user=user)
return user
return False
示例15: confirm_email
# 需要导入模块: from django.contrib.auth.models import Permission [as 别名]
# 或者: from django.contrib.auth.models.Permission import DoesNotExist [as 别名]
def confirm_email(self, confirmation_key):
"""
Confirm an email address by checking a ``confirmation_key``.
A valid ``confirmation_key`` will set the newly wanted e-mail
address as the current e-mail address. Returns the user after
success or ``False`` when the confirmation key is
invalid. Also sends the ``confirmation_complete`` signal.
:param confirmation_key:
String containing the secret nonce that is used for verification.
:return:
The verified :class:`User` or ``False`` if not successful.
"""
if NONCE_RE.search(confirmation_key):
try:
userena = self.get(
email_confirmation_key=confirmation_key,
email_unconfirmed__isnull=False,
)
except self.model.DoesNotExist:
return False
else:
user = userena.user
old_email = user.email
user.email = userena.email_unconfirmed
userena.email_unconfirmed, userena.email_confirmation_key = "", ""
userena.save(using=self._db)
user.save(using=self._db)
# Send the confirmation_complete signal
userena_signals.confirmation_complete.send(
sender=None, user=user, old_email=old_email
)
return user
return False