Python django.contrib.auth.models.Permission.DoesNotExist() Examples
The following are 27
code examples of django.contrib.auth.models.Permission.DoesNotExist().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.contrib.auth.models.Permission
, or try the search function
.
Example #1
Source File: views.py From allianceauth with GNU General Public License v2.0 | 6 votes |
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)
Example #2
Source File: 0074_create_light_admin_group.py From linkedevents with MIT License | 6 votes |
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])
Example #3
Source File: managers.py From django-userena-ce with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #4
Source File: managers.py From django-userena-ce with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #5
Source File: managers.py From django-userena-ce with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #6
Source File: 0012_add_permission_view_xform.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
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
Example #7
Source File: handlers.py From allianceauth with GNU General Public License v2.0 | 5 votes |
def emit(self, record): from django.contrib.auth.models import User, Permission from django.db.models import Q from . import notify from .models import Notification try: perm = Permission.objects.get(codename="logging_notifications") message = record.getMessage() if record.exc_text: message += "\n\n" message = message + record.exc_text users = User.objects.filter( Q(groups__permissions=perm) | Q(user_permissions=perm) | Q(is_superuser=True)).distinct() for user in users: notify( user, "%s [%s:%s]" % (record.levelname, record.funcName, record.lineno), level=str([item[0] for item in Notification.LEVEL_CHOICES if item[1] == record.levelname][0]), message=message ) except Permission.DoesNotExist: pass
Example #8
Source File: upgrade_from_django_netjsongraph.py From openwisp-network-topology with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _get_updated_permission_list( self, permission_data, permissions_list, contenttype_data ): permit_list = [] for permit_pk in permissions_list: for item in permission_data: if item['pk'] == permit_pk: for content in contenttype_data: if item['fields']['content_type'] == content['pk']: permit_app_label = content['fields']['app_label'] if permit_app_label == 'django_netjsongraph': permit_app_label = self.app_label elif ( content['fields']['model'] in ['user', 'group'] and permit_app_label == 'auth' ): permit_app_label = self.app_label_users try: permit_list.append( Permission.objects.get( content_type__app_label=permit_app_label, codename=item['fields']['codename'], ).pk ) except Permission.DoesNotExist: # pragma: nocover pass return permit_list
Example #9
Source File: 0005_default_operator_permission.py From openwisp-network-topology with BSD 3-Clause "New" or "Revised" License | 5 votes |
def assign_permissions_to_groups(apps, schema_editor): create_default_permissions(apps, schema_editor) operators_and_admin_can_change = ['link', 'node'] operators_read_only_admins_manage = ['topology'] manage_operations = ['add', 'change', 'delete'] Group = apps.get_model('openwisp_users', 'Group') try: admin = Group.objects.get(name='Administrator') operator = Group.objects.get(name='Operator') # consider failures custom cases # that do not have to be dealt with except Group.DoesNotExist: return for model_name in operators_and_admin_can_change: for operation in manage_operations: permission = Permission.objects.get( codename='{}_{}'.format(operation, model_name) ) admin.permissions.add(permission.pk) operator.permissions.add(permission.pk) for model_name in operators_read_only_admins_manage: try: permission = Permission.objects.get(codename="view_{}".format(model_name)) operator.permissions.add(permission.pk) except Permission.DoesNotExist: pass for operation in manage_operations: admin.permissions.add( Permission.objects.get( codename="{}_{}".format(operation, model_name) ).pk )
Example #10
Source File: __init__.py From openwisp-controller with GNU General Public License v3.0 | 5 votes |
def assign_permissions_to_groups(apps, schema_editor): create_default_permissions(apps, schema_editor) operators_and_admins_can_change = ['device', 'config', 'template'] operators_read_only_admins_manage = ['vpn'] manage_operations = ['add', 'change', 'delete'] Group = apps.get_model('openwisp_users', 'Group') try: admin = Group.objects.get(name='Administrator') operator = Group.objects.get(name='Operator') # consider failures custom cases # that do not have to be dealt with except Group.DoesNotExist: return for model_name in operators_and_admins_can_change: for operation in manage_operations: permission = Permission.objects.get( codename='{}_{}'.format(operation, model_name) ) admin.permissions.add(permission.pk) operator.permissions.add(permission.pk) for model_name in operators_read_only_admins_manage: try: permission = Permission.objects.get(codename='view_{}'.format(model_name)) operator.permissions.add(permission.pk) except Permission.DoesNotExist: pass for operation in manage_operations: admin.permissions.add( Permission.objects.get( codename='{}_{}'.format(operation, model_name) ).pk )
Example #11
Source File: __init__.py From openwisp-controller with GNU General Public License v3.0 | 5 votes |
def assign_permissions_to_groups(apps, schema_editor): create_default_permissions(apps, schema_editor) operators_read_only_admins_manage = ['ca', 'cert'] manage_operations = ['add', 'change', 'delete'] Group = apps.get_model('openwisp_users', 'Group') try: admin = Group.objects.get(name='Administrator') operator = Group.objects.get(name='Operator') # consider failures custom cases # that do not have to be dealt with except Group.DoesNotExist: return for model_name in operators_read_only_admins_manage: try: permission = Permission.objects.get(codename='view_{}'.format(model_name)) operator.permissions.add(permission.pk) except Permission.DoesNotExist: pass for operation in manage_operations: admin.permissions.add( Permission.objects.get( codename='{}_{}'.format(operation, model_name) ).pk )
Example #12
Source File: managers.py From django-userena-ce with BSD 3-Clause "New" or "Revised" License | 5 votes |
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
Example #13
Source File: managers.py From django-userena-ce with BSD 3-Clause "New" or "Revised" License | 5 votes |
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
Example #14
Source File: initgroups.py From guacozy with MIT License | 5 votes |
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))
Example #15
Source File: helpers.py From wagtailmodeladmin with MIT License | 5 votes |
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)
Example #16
Source File: common.py From autoAdmin with GNU Lesser General Public License v3.0 | 5 votes |
def get_permission_obj(pid): try: return Permission.objects.get(pk=pid) except Permission.DoesNotExist: return None
Example #17
Source File: test_helpers.py From richie with MIT License | 5 votes |
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", )
Example #18
Source File: helpers.py From richie with MIT License | 5 votes |
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
Example #19
Source File: helpers.py From django-protector with MIT License | 5 votes |
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
Example #20
Source File: views_permission.py From boss with Apache License 2.0 | 5 votes |
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")
Example #21
Source File: helpers.py From richie with MIT License | 4 votes |
def recursive_page_creation(site, pages_info, parent=None): """ Recursively create page following tree structure with parent/children. Arguments: site (django.contrib.sites.models.Site): Site object which page will be linked to. pages_info (dict): Page items to create recursively such as 'children' key value can be a dict to create child pages. The current page is given to children for parent relation. Keyword Arguments: parent (cms.models.pagemodel.Page): Page used as a parent to create page item from `pages` argument. Returns: dict: mapping of the page names passed in argument and the created page instances. """ pages = {} for name, kwargs in pages_info.items(): children = kwargs.pop("children", None) if kwargs.get("is_homepage"): query_params = {"is_home": True} else: query_params = {"reverse_id": name} try: page = Page.objects.get( publisher_is_draft=True, node__site=site, **query_params ) except Page.DoesNotExist: page = create_i18n_page( site=site, parent=parent, published=True, reverse_id=name, **kwargs ) pages[name] = page # Create children if children: children_pages = recursive_page_creation(site, children, parent=page) for child_name in children_pages: if child_name in pages: raise ImproperlyConfigured( "Page names should be unique: {:s}".format(child_name) ) pages.update(children_pages) return pages
Example #22
Source File: test_commands.py From django-userena-ce with BSD 3-Clause "New" or "Revised" License | 4 votes |
def test_incomplete_permissions(self): # Delete the neccesary permissions profile_model_obj = get_profile_model() content_type_profile = ContentType.objects.get_for_model(profile_model_obj) content_type_user = ContentType.objects.get_for_model(User) for model, perms in ASSIGNED_PERMISSIONS.items(): if model == "profile": content_type = content_type_profile else: content_type = content_type_user for perm in perms: Permission.objects.get(name=perm[1], content_type=content_type).delete() # Check if they are they are back for model, perms in ASSIGNED_PERMISSIONS.items(): if model == "profile": content_type = content_type_profile else: content_type = content_type_user for perm in perms: try: perm = Permission.objects.get( name=perm[1], content_type=content_type ) except Permission.DoesNotExist: pass else: self.fail("Found %s: " % perm) # Repair them call_command("check_permissions", test=True) # Check if they are they are back for model, perms in ASSIGNED_PERMISSIONS.items(): if model == "profile": content_type = content_type_profile else: content_type = content_type_user for perm in perms: try: perm = Permission.objects.get( name=perm[1], content_type=content_type ) except Permission.DoesNotExist: self.fail()
Example #23
Source File: views_permission.py From boss with Apache License 2.0 | 4 votes |
def delete(self, request): """ Delete permissions for a resource object Remove specific permissions for a existing group and resource object Args: request: Django rest framework request Returns: Http status code """ if 'group' not in request.query_params: return BossHTTPError("Group are not included in the request", ErrorCodes.INVALID_URL) if 'collection' not in request.query_params: return BossHTTPError("Invalid resource or missing resource name in request", ErrorCodes.INVALID_URL) group_name = request.query_params.get('group', None) collection = request.query_params.get('collection', None) experiment = request.query_params.get('experiment', None) channel = request.query_params.get('channel', None) try: if not check_is_member_or_maintainer(request.user, group_name): return BossHTTPError('The user {} is not a member or maintainer of the group {} '. format(request.user.username, group_name), ErrorCodes.MISSING_PERMISSION) resource_object = self.get_object(collection, experiment, channel) if resource_object is None: return BossHTTPError("Unable to validate the resource", ErrorCodes.UNABLE_TO_VALIDATE) if request.user.has_perm("remove_group", resource_object[0]): BossPermissionManager.delete_all_permissions_group(group_name, resource_object[0]) return Response(status=status.HTTP_204_NO_CONTENT) else: return BossPermissionError('remove group', resource_object[0].name) except Group.DoesNotExist: return BossGroupNotFoundError(group_name) except Permission.DoesNotExist: return BossHTTPError("Invalid permissions in post".format(request.data['permissions']), ErrorCodes.UNRECOGNIZED_PERMISSION) except Exception as e: return BossHTTPError("{}".format(e), ErrorCodes.UNHANDLED_EXCEPTION) except BossError as err: return err.to_http()
Example #24
Source File: views_permission.py From boss with Apache License 2.0 | 4 votes |
def patch(self, request): """ Patch permissions for a resource Remove specific permissions for a existing group and resource object Args: request: Django rest framework request Returns: Http status code """ if 'permissions' not in request.data: return BossHTTPError("Permission are not included in the request", ErrorCodes. UNABLE_TO_VALIDATE) else: perm_list = dict(request.data)['permissions'] if 'group' not in request.data: return BossHTTPError("Group are not included in the request", ErrorCodes. UNABLE_TO_VALIDATE) if 'collection' not in request.data: return BossHTTPError("Invalid resource or missing resource name in request", ErrorCodes. UNABLE_TO_VALIDATE) group_name = request.data.get('group', None) collection = request.data.get('collection', None) experiment = request.data.get('experiment', None) channel = request.data.get('channel', None) try: # public group can only have read permission if group_name == PUBLIC_GRP and (len(perm_list) != 1 or perm_list[0] != 'read'): return BossHTTPError("The public group can only have read permissions", ErrorCodes.INVALID_POST_ARGUMENT) # If the user is not a member or maintainer of the group, they cannot patch permissions if not check_is_member_or_maintainer(request.user, group_name): return BossHTTPError('The user {} is not a member or maintainer of the group {} '. format(request.user.username, group_name), ErrorCodes.MISSING_PERMISSION) resource_object = self.get_object(collection, experiment, channel) if resource_object is None: return BossHTTPError("Unable to validate the resource", ErrorCodes.UNABLE_TO_VALIDATE) resource = resource_object[0] # remove all existing permission for the group if request.user.has_perm("remove_group", resource) and request.user.has_perm("assign_group", resource): BossPermissionManager.delete_all_permissions_group(group_name, resource) BossPermissionManager.add_permissions_group(group_name, resource, perm_list) return Response(status=status.HTTP_200_OK) else: return BossPermissionError('remove group', resource.name) except Group.DoesNotExist: return BossGroupNotFoundError(group_name) except Permission.DoesNotExist: return BossHTTPError("Invalid permissions in post".format(request.data['permissions']), ErrorCodes.UNRECOGNIZED_PERMISSION) except BossError as err: return err.to_http()
Example #25
Source File: views_permission.py From boss with Apache License 2.0 | 4 votes |
def post(self, request): """ Add permissions to a resource Add new permissions for a existing group and resource object Args: request: Django rest framework request Returns: Http status code """ if 'permissions' not in request.data: return BossHTTPError("Permission are not included in the request", ErrorCodes.INVALID_URL) else: perm_list = dict(request.data)['permissions'] if 'group' not in request.data: return BossHTTPError("Group are not included in the request", ErrorCodes.INVALID_URL) if 'collection' not in request.data: return BossHTTPError("Invalid resource or missing resource name in request", ErrorCodes.INVALID_URL) group_name = request.data.get('group', None) collection = request.data.get('collection', None) experiment = request.data.get('experiment', None) channel = request.data.get('channel', None) try: # public group can only have read permission if group_name == PUBLIC_GRP and not (set(perm_list).issubset({'read', 'read_volumetric_data'})): return BossHTTPError("The public group can only have read permissions", ErrorCodes.INVALID_POST_ARGUMENT) # If the user is not a member or maintainer of the group, they cannot assign permissions if not check_is_member_or_maintainer(request.user, group_name): return BossHTTPError('The user {} is not a member or maintainer of the group {} '. format(request.user.username, group_name), ErrorCodes.MISSING_PERMISSION) resource_object = self.get_object(collection, experiment, channel) if resource_object is None: return BossHTTPError("Unable to validate the resource", ErrorCodes.UNABLE_TO_VALIDATE) resource = resource_object[0] if request.user.has_perm("assign_group", resource): BossPermissionManager.add_permissions_group(group_name, resource, perm_list) return Response(status=status.HTTP_201_CREATED) else: return BossPermissionError('assign group', collection) except Group.DoesNotExist: return BossGroupNotFoundError(group_name) except Permission.DoesNotExist: return BossHTTPError("Invalid permissions in post".format(request.data['permissions']), ErrorCodes.UNRECOGNIZED_PERMISSION) except BossError as err: return err.to_http()
Example #26
Source File: __init__.py From openwisp-users with BSD 3-Clause "New" or "Revised" License | 4 votes |
def create_default_groups(apps, schema_editor): org_model = swapper.get_model_name('openwisp_users', 'organization') model_app_label = swapper.split(org_model)[0] group = apps.get_model(model_app_label, 'group') # To populate all the permissions for app_config in apps.get_app_configs(): app_config.models_module = True create_permissions(app_config, apps=apps, verbosity=0) app_config.models_module = None operator = group.objects.filter(name='Operator') if operator.count() == 0: operator = group.objects.create(name='Operator') admin = group.objects.filter(name='Administrator') if admin.count() == 0: admin = group.objects.create(name='Administrator') permissions = [ Permission.objects.get( content_type__app_label=model_app_label, codename='add_user' ).pk, Permission.objects.get( content_type__app_label=model_app_label, codename='change_user' ).pk, Permission.objects.get( content_type__app_label=model_app_label, codename='change_organizationuser', ).pk, Permission.objects.get( content_type__app_label=model_app_label, codename='delete_organizationuser', ).pk, Permission.objects.get( content_type__app_label=model_app_label, codename='add_organizationuser', ).pk, ] try: permissions += [ Permission.objects.get( content_type__app_label=model_app_label, codename='view_user' ).pk, Permission.objects.get( content_type__app_label=model_app_label, codename='view_group' ).pk, Permission.objects.get( content_type__app_label=model_app_label, codename='view_organizationuser', ).pk, ] except Permission.DoesNotExist: pass admin.permissions.set(permissions)
Example #27
Source File: __init__.py From openwisp-radius with GNU General Public License v3.0 | 4 votes |
def assign_permissions_to_groups(apps, schema_editor): create_default_permissions(apps, schema_editor) Group = get_swapped_model(apps, 'openwisp_users', 'Group') try: admin = Group.objects.get(name='Administrator') operator = Group.objects.get(name='Operator') # consider failures custom cases # that do not have to be dealt with except Group.DoesNotExist: return operators_and_admins_can_manage = ['radiuspostauth', 'radiusaccounting'] operators_read_only_admins_manage = [ 'radiuscheck', 'radiusreply', 'radiusgroup', 'radiusgroupcheck', 'radiusgroupreply', 'radiususergroup', 'nas', 'radiusbatch', 'organizationradiussettings', ] manage_operations = ['add', 'change', 'delete'] for action in manage_operations: for model_name in operators_and_admins_can_manage: permission = Permission.objects.get( codename='{}_{}'.format(action, model_name) ) admin.permissions.add(permission.pk) operator.permissions.add(permission.pk) for model_name in operators_read_only_admins_manage: try: permission = Permission.objects.get(codename='view_{}'.format(model_name)) operator.permissions.add(permission.pk) except Permission.DoesNotExist: pass for action in manage_operations: permission_ad = Permission.objects.get( codename='{}_{}'.format(action, model_name) ) admin.permissions.add(permission_ad.pk)