def create_permissions_respecting_proxy(app, created_models, verbosity, **kwargs): ''' An alternative to create_permissions found in django.contrib.auth. This one doesn't use the ContentType.objects.get_for_model which resolves the klass to the base model. Instead it returns the content type for the proxy model. ''' from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission app_models = get_models(app) if not app_models: return for klass in app_models: # The difference is here: # ctype = ContentType.objects.get_for_model(klass) opts = klass._meta ctype, created = ContentType.objects.get_or_create( app_label=opts.app_label, model=opts.object_name.lower(), defaults={'name': smart_text(opts.verbose_name_raw)}, ) # (end of difference) for codename, name in _get_all_permissions(klass._meta): p, created = Permission.objects.get_or_create( codename=codename, content_type__pk=ctype.id, defaults={ 'name': name, 'content_type': ctype }) if created and verbosity >= 2: print("Adding permission '%s'" % p)
def handle(self, *args, **options): # We need to execute the post migration callback manually in order # to append the view permission on the proxy model. Then the following # script will create the appropriate content type and move the # permissions under this. If we don't call the callback the script # will create only the basic permissions (add, change, delete) update_permissions( apps.get_app_config('admin_view_permission'), apps.get_app_config('admin_view_permission'), verbosity=1, interactive=True, using='default', ) for model in apps.get_models(): opts = model._meta ctype, created = ContentType.objects.get_or_create( app_label=opts.app_label, model=opts.object_name.lower(), ) for codename, name in _get_all_permissions(opts): perm, created = Permission.objects.get_or_create( codename=codename, content_type=ctype, defaults={'name': name}, ) if created: self.delete_parent_perms(perm) self.stdout.write('Adding permission {}\n'.format(perm))
def create_permissions_respecting_proxy(app, created_models, verbosity, **kwargs): ''' An alternative to create_permissions found in django.contrib.auth. This one doesn't use the ContentType.objects.get_for_model which resolves the klass to the base model. Instead it returns the content type for the proxy model. ''' from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission app_models = get_models(app) if not app_models: return for klass in app_models: # The difference is here: #ctype = ContentType.objects.get_for_model(klass) opts = klass._meta ctype, created = ContentType.objects.get_or_create( app_label = opts.app_label, model = opts.object_name.lower(), defaults = {'name': smart_unicode(opts.verbose_name_raw)}, ) # (end of difference) for codename, name in _get_all_permissions(klass._meta): p, created = Permission.objects.get_or_create(codename=codename, content_type__pk=ctype.id, defaults={'name': name, 'content_type': ctype}) if created and verbosity >= 2: print "Adding permission '%s'" % p
def permission_data(klass): """ Returns permission data in the form (ContentType(model), [(Permission.codename, Permission.name), ...]) """ ct = ct_manager.get_for_model(klass) p = _get_all_permissions(klass._meta, ct) return ct, p
def check_content_type(): for model in apps.get_models(): opts = model._meta if ContentType.objects.filter(app_label=opts.app_label, model=opts.object_name.lower()).exists(): if model is ProxyTest: ctype = ContentType.objects.get(app_label=opts.app_label, model=opts.object_name.lower()) for codename, name in _get_all_permissions(opts, ctype): print codename, name
def handle_noargs(self, **options): app = get_app('services') try: boris_config = apps.get_app_config('boris') except: raise EnvironmentError( 'Cannot find app `boris`. App configs are: %s' % apps.get_app_configs()) update_contenttypes(boris_config, 2, interactive=False) app_models = models.get_models(app) # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = list() # The codenames and ctypes that should exist. ctypes = set() for model in app_models: opts = model._meta # We can't use `get_for_model` here since it doesn't return # the correct `ContentType` for proxy models. # see https://code.djangoproject.com/ticket/17648 app_label, model = opts.app_label, opts.object_name.lower() if app_label == 'services' and model == 'encounter': ctype = ContentType.objects.get_by_natural_key( app_label, model) ctypes.add(ctype) for perm in _get_all_permissions(opts, model): searched_perms.append((ctype, perm)) # Find all the Permissions that have a content_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_perms = set( Permission.objects.filter(content_type__in=ctypes, ).values_list( "content_type", "codename")) group, created = Group.objects.get_or_create(name=u'Terén') print 'group: %s' % group if created: print 'ERROR: skupina Teren neexistovala!' return for ctype, (codename, name) in searched_perms: if (ctype.pk, codename) not in all_perms: Permission.objects.filter(codename=codename, name=name).delete() perm = Permission.objects.create(codename=codename, name=name, content_type=ctype) group.permissions.add(perm) sys.stdout.write("Adding encounter permission '%s'" % perm) for perm in Permission.objects.filter( codename__endswith='_groupcontact'): group.permissions.add(perm) sys.stdout.write("Adding group encounter permission '%s'" % perm) for perm in Permission.objects.filter(codename__endswith='_encounter'): group.permissions.add(perm) sys.stdout.write("Adding service permission '%s'" % perm)
def get_searched_permissions(ctypes): """ Return all permissions that should exist for existing contenttypes """ # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = list() for ctype, klass in ctypes: for perm in _get_all_permissions(klass._meta): searched_perms.append((ctype, perm)) return searched_perms
def handle_noargs(self, **options): app = get_app('services') try: boris_config = apps.get_app_config('boris') except: raise EnvironmentError('Cannot find app `boris`. App configs are: %s' % apps.get_app_configs()) update_contenttypes(boris_config, 2, interactive=False) app_models = models.get_models(app) # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = list() # The codenames and ctypes that should exist. ctypes = set() for model in app_models: opts = model._meta # We can't use `get_for_model` here since it doesn't return # the correct `ContentType` for proxy models. # see https://code.djangoproject.com/ticket/17648 app_label, model = opts.app_label, opts.object_name.lower() if app_label == 'services' and model == 'encounter': ctype = ContentType.objects.get_by_natural_key(app_label, model) ctypes.add(ctype) for perm in _get_all_permissions(opts, model): searched_perms.append((ctype, perm)) # Find all the Permissions that have a content_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_perms = set(Permission.objects.filter( content_type__in=ctypes, ).values_list( "content_type", "codename" )) group, created = Group.objects.get_or_create(name=u'Terén') print 'group: %s' % group if created: print 'ERROR: skupina Teren neexistovala!' return for ctype, (codename, name) in searched_perms: if (ctype.pk, codename) not in all_perms: Permission.objects.filter(codename=codename, name=name).delete() perm = Permission.objects.create(codename=codename, name=name, content_type=ctype) group.permissions.add(perm) sys.stdout.write("Adding encounter permission '%s'" % perm) for perm in Permission.objects.filter(codename__endswith='_groupcontact'): group.permissions.add(perm) sys.stdout.write("Adding group encounter permission '%s'" % perm) for perm in Permission.objects.filter(codename__endswith='_encounter'): group.permissions.add(perm) sys.stdout.write("Adding service permission '%s'" % perm)
def handle(self, *args, **options): for model in apps.get_models(): opts = model._meta sys.stdout.write('{}-{}\n'.format(opts.app_label, opts.object_name.lower())) ctype, created = ContentType.objects.get_or_create( app_label=opts.app_label, model=opts.object_name.lower()) argspecs = inspect.getargspec(_get_all_permissions) if len(argspecs[0]) == 2: # django < 1.10 all_permissions = _get_all_permissions(opts, ctype) else: all_permissions = _get_all_permissions(opts) for codename, name in all_permissions: sys.stdout.write(' --{}\n'.format(codename)) p, created = Permission.objects.get_or_create( codename=codename, content_type=ctype, defaults={'name': name}) if created: sys.stdout.write('Adding permission {}\n'.format(p))
def handle(self, *args, **options): for model in apps.get_models(): opts = model._meta ctype, created = ContentType.objects.get_or_create( app_label=opts.app_label, model=opts.object_name.lower()) for codename, name in _get_all_permissions(opts): p, created = Permission.objects.get_or_create( codename=codename, content_type=ctype, defaults={'name': name}) if created: sys.stdout.write('Adding permission {}\n'.format(p))
def create_perms_post_migrate(sapl_app_config): searched_perms = list() # The codenames and ctypes that should exist. ctypes = set() for klass in list(sapl_app_config.get_models()): opts = klass._meta permissions = ( ("list_" + opts.model_name, string_concat( _('Visualizaçao da lista de'), ' ', opts.verbose_name_plural)), ("detail_" + opts.model_name, string_concat( _('Visualização dos detalhes de'), ' ', opts.verbose_name_plural)), ) opts.permissions = tuple( set(list(permissions) + list(opts.permissions))) if opts.proxy: # Force looking up the content types in the current database # before creating foreign keys to them. app_label, model = opts.app_label, opts.model_name try: ctype = ContentType.objects.get_by_natural_key( app_label, model) except: ctype = ContentType.objects.create( app_label=app_label, model=model) else: ctype = ContentType.objects.get_for_model(klass) ctypes.add(ctype) for perm in _get_all_permissions(klass._meta, ctype): searched_perms.append((ctype, perm)) all_perms = set(Permission.objects.filter( content_type__in=ctypes, ).values_list( "content_type", "codename" )) perms = [ Permission(codename=codename, name=name, content_type=ct) for ct, (codename, name) in searched_perms if (ct.pk, codename) not in all_perms ] Permission.objects.bulk_create(perms)
def create_proxy_permissions(app, **kwargs): """ Creates permissions for proxy models which are not created automatically by `django.contrib.auth.management.create_permissions`. see https://code.djangoproject.com/ticket/11154 This method is inspired by `django.contrib.auth.managment.create_permissions`. Since we can't rely on `get_for_model' we must fallback to `get_by_natural_key`. However, this method doesn't automatically create missing `ContentType` so we must ensure all the model's `ContentType` are created before running this method. We do so by unregistering the `update_contenttypes` `post_syncdb` signal and calling it in here just before doing everything. Adapted from http://djangosnippets.org/snippets/2677/. """ app_mod = models.get_app(app) app_models = models.get_models(app_mod) # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = list() # The codenames and ctypes that should exist. ctypes = set() for model in app_models: opts = model._meta if opts.proxy: # We can't use `get_for_model` here since it doesn't return # the correct `ContentType` for proxy models. # see https://code.djangoproject.com/ticket/17648 app_label, model = opts.app_label, opts.object_name.lower() ctype = ContentType.objects.get_by_natural_key(app_label, model) ctypes.add(ctype) for perm in _get_all_permissions(opts): searched_perms.append((ctype, perm)) # Find all the Permissions that have a content_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_perms = set(Permission.objects.filter( content_type__in=ctypes, ).values_list( "content_type", "codename" )) objs = [ Permission(codename=codename, name=name, content_type=ctype) for ctype, (codename, name) in searched_perms if (ctype.pk, codename) not in all_perms ] for ctype, (codename, name) in searched_perms: if (ctype.pk, codename) not in all_perms: Permission.objects.get_or_create(codename=codename, name=name, content_type=ctype)
def handle(self, *args, **options): for model in get_models(): opts = model._meta ctype, created = ContentType.objects.get_or_create( app_label=opts.app_label, model=opts.object_name.lower(), defaults={'name': smart_unicode(opts.verbose_name_raw)}) for codename, name in _get_all_permissions(opts): p, created = Permission.objects.get_or_create( codename=codename, content_type=ctype, defaults={'name': name}) if created: sys.stdout.write('Adding permission {}\n'.format(p))
def create_permissions(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, apps=global_apps, **kwargs): if not app_config.models_module: return app_label = app_config.label try: app_config = apps.get_app_config(app_label) ContentType = apps.get_model('contenttypes', 'ContentType') Permission = apps.get_model('auth', 'Permission') except LookupError: return if not router.allow_migrate_model(using, Permission): return # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = [] # The codenames and ctypes that should exist. ctypes = set() for klass in app_config.get_models(): # Force looking up the content types in the current database # before creating foreign keys to them. ctype = ContentType.objects.db_manager(using).get_for_model(klass) ctypes.add(ctype) klass._meta.default_permissions = ('view', 'add', 'change', 'delete') for perm in _get_all_permissions(klass._meta): searched_perms.append((ctype, perm)) # Find all the Permissions that have a content_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_perms = set(Permission.objects.using(using).filter( content_type__in=ctypes, ).values_list( "content_type", "codename" )) perms = [ Permission(codename=codename, name=name, content_type=ct) for ct, (codename, name) in searched_perms if (ct.pk, codename) not in all_perms ] Permission.objects.using(using).bulk_create(perms) if verbosity >= 2: for perm in perms: print("Adding permission '%s'" % perm)
def handle(self, *args, **options): for model in get_models(): opts = model._meta ctype, created = ContentType.objects.get_or_create( app_label=opts.app_label, model=opts.object_name.lower(), defaults={'name': smart_unicode(opts.verbose_name_raw)}) for codename, name in _get_all_permissions(opts, ctype): p, created = Permission.objects.get_or_create( codename=codename, content_type=ctype, defaults={'name': name}) if created: if options["verbosity"] >= 1: sys.stdout.write('Adding permission {}\n'.format(p))
def handle_app(self, app, **options): app_name = app.__name__.split('.')[-2] # app is the models module for ctype in ContentType.objects.filter(app_label=app_name, permission__isnull=True): for codename, name in _get_all_permissions( ctype.model_class()._meta): p, created = Permission.objects.get_or_create( codename=codename, content_type__pk=ctype.id, defaults={ 'name': name, 'content_type': ctype }) if created: if options.get('verbosity', 1) >= 1: self.stdout.write("Created: %s\n" % (p, ))
def createProxyPermission(): for model in apps.get_models(): opts = model._meta ctype, created = ContentType.objects.get_or_create( app_label=opts.app_label, model=opts.object_name.lower(), defaults={"name": smart_unicode(opts.verbose_name_raw)}, ) if created: print "Create ContentType: %s" % ctype for codename, name in _get_all_permissions(opts, ctype): p, created = Permission.objects.get_or_create( codename=codename, content_type=ctype, defaults={"name": name} ) if created: sys.stdout.write("Adding permission {}\n".format(p))
def create_permissions(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs): """Create permissions on django 1.10+.""" if not app_config.models_module: return try: ContentType = apps.get_model('contenttypes', 'ContentType') Permission = apps.get_model('auth', 'Permission') except LookupError: return if not router.allow_migrate_model(using, Permission): return searched_perms = list() # (content_type, (codename, name)) ctypes = set() # The codenames and ctypes that should exist. for klass in app_config.get_models(): # ctype = ContentType.objects.db_manager(using).get_for_model(klass) opts = klass._meta ctype, _ = ContentType.objects.get_or_create( app_label=opts.app_label, model=opts.object_name.lower()) ctypes.add(ctype) from django.contrib.auth.management import _get_all_permissions for perm in _get_all_permissions(klass._meta): searched_perms.append((ctype, perm)) all_perms = set( Permission.objects.using(using).filter( content_type__in=ctypes, ).values_list("content_type", "codename")) perms = [ Permission(codename=codename, name=name, content_type=ct) for ct, (codename, name) in searched_perms if (ct.pk, codename) not in all_perms ] Permission.objects.using(using).bulk_create(perms) if verbosity >= 2: for perm in perms: print("Adding permission '%s'" % perm)
def create_proxy_permissions(app, created_models, verbosity, **kwargs): """ Creates permissions for proxy models which are not created automatically by `django.contrib.auth.management.create_permissions`. see https://code.djangoproject.com/ticket/11154 This method is inspired by `django.contrib.auth.managment.create_permissions`. Since we can't rely on `get_for_model' we must fallback to `get_by_natural_key`. However, this method doesn't automatically create missing `ContentType` so we must ensure all the model's `ContentType` are created before running this method. We do so by unregistering the `update_contenttypes` `post_syncdb` signal and calling it in here just before doing everything. """ update_contenttypes(app, created_models, verbosity, **kwargs) app_models = models.get_models(app) # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = list() # The codenames and ctypes that should exist. ctypes = set() for model in app_models: opts = model._meta if opts.proxy: # We can't use `get_for_model` here since it doesn't return # the correct `ContentType` for proxy models. # see https://code.djangoproject.com/ticket/17648 app_label, model = opts.app_label, opts.object_name.lower() ctype = ContentType.objects.get_by_natural_key(app_label, model) ctypes.add(ctype) for perm in _get_all_permissions(opts): searched_perms.append((ctype, perm)) # Find all the Permissions that have a content_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_perms = set(Permission.objects.filter( content_type__in=ctypes, ).values_list( "content_type", "codename" )) for ctype, (codename, name) in searched_perms: if (ctype.pk, codename) not in all_perms: Permission.objects.filter(codename=codename, name=name).delete() perm = Permission.objects.create(codename=codename, name=name, content_type=ctype) if verbosity >= 2: sys.stdout.write("Adding permission '%s'" % perm)
def handle(self, *args, **options): if options['apps']: app_names = options['apps'].split(',') apps = [django_apps.get_app_config(x) for x in app_names] else: apps = django_apps.get_app_configs() if options['create_only']: do_create, do_update = True, False elif options['update_only']: do_create, do_update = False, True else: do_create, do_update = True, True for app in apps: if DJANGO_VERSION < (2, 2): # see https://github.com/django/django/commit/bec651a427fc032d9115d30c8c5d0e702d754f6c # Ensure that contenttypes are created for this app. Needed if # 'django.contrib.auth' is in INSTALLED_APPS before # 'django.contrib.contenttypes'. from django.contrib.contenttypes.management import create_contenttypes create_contenttypes(app, verbosity=options['verbosity']) if do_create: # create permissions if they do not exist create_permissions(app, options['verbosity']) if do_update: # update permission name's if changed for model in app.get_models(): content_type = ContentType.objects.get_for_model(model) for codename, name in _get_all_permissions(model._meta): try: permission = Permission.objects.get( codename=codename, content_type=content_type) except Permission.DoesNotExist: continue if permission.name != name: old_str = str(permission) permission.name = name if options['verbosity'] >= 2: self.stdout.write( self.style.SUCCESS( "Update permission '%s' to '%s'" % (old_str, permission))) permission.save()
def handle(self, *args, **options): for model in apps.get_models(): # noinspection PyProtectedMember opts = model._meta ctype, created = ContentType.objects.get_or_create( app_label=opts.app_label, model=opts.object_name.lower(), defaults={"name": smart_text(opts.verbose_name_raw)}, ) for codename, name in _get_all_permissions(opts, ctype): p, created = Permission.objects.get_or_create( codename=codename, content_type=ctype, defaults={"name": name}) if created: sys.stdout.write("Adding permission {}\n".format(p))
def handle(self, *args, **options): # Don't exclude models without permissions here, as it would not delete # stale ones if all get removed at once: for model in apps.get_models(): content_type = ContentType.objects.get_for_model(model) # This will raise an exception if 2 permissions have same codename: try: _all_permissions = management._get_all_permissions(model._meta) except ValueError as e: if str(e) == 'too many values to unpack': print("Error: Check permissions tuple of '%s', missing a comma? " % model.__name__, \ "Make sure the surrounding tuple has a trailing comma if it holds only a single permission.") return else: raise self._create_non_existing_permissions(model, content_type) # self._delete_stale_permissions(model, content_type) # not work with proxy models self._update_changed_names(model, content_type)
def handle(self, *args, **options): for model in apps.get_models(): opts = model._meta sys.stdout.write("{}-{}\n".format(opts.app_label, opts.object_name.lower())) ctype, created = ContentType.objects.get_or_create( app_label=opts.app_label, model=opts.object_name.lower(), ) for codename, name in _get_all_permissions(opts): sys.stdout.write(" --{}\n".format(codename)) p, created = Permission.objects.get_or_create( codename=codename, content_type=ctype, defaults={"name": name}, ) if created: sys.stdout.write("Adding permission {}\n".format(p))
def handle(self, *args, **options): if options['apps']: app_names = options['apps'].split(',') apps = [django_apps.get_app_config(x) for x in app_names] else: apps = django_apps.get_app_configs() if options['create_only']: do_create, do_update = True, False elif options['update_only']: do_create, do_update = False, True else: do_create, do_update = True, True for app in apps: if DJANGO_VERSION < (2, 2): # see https://github.com/django/django/commit/bec651a427fc032d9115d30c8c5d0e702d754f6c # Ensure that contenttypes are created for this app. Needed if # 'django.contrib.auth' is in INSTALLED_APPS before # 'django.contrib.contenttypes'. from django.contrib.contenttypes.management import create_contenttypes create_contenttypes(app, verbosity=options['verbosity']) if do_create: # create permissions if they do not exist create_permissions(app, options['verbosity']) if do_update: # update permission name's if changed for model in app.get_models(): content_type = ContentType.objects.get_for_model(model) for codename, name in _get_all_permissions(model._meta): try: permission = Permission.objects.get(codename=codename, content_type=content_type) except Permission.DoesNotExist: continue if permission.name != name: old_str = str(permission) permission.name = name if options['verbosity'] >= 2: self.stdout.write(self.style.SUCCESS("Update permission '%s' to '%s'" % (old_str, permission))) permission.save()
def _get_project_specific_permissions(model, is_concretely_inherited=False): from ..models.auth import ProjectPermissionsMixin # Only deal with models which subclass ProjectPermissionsMixin if not issubclass(model, ProjectPermissionsMixin): return [] ct = ContentType.objects.get_for_model(model) auto_model_perms = _get_all_permissions(model._meta, ct) ignored_model_perms = IGNORED_PERMISSIONS.get( '{}.{}'.format(model._meta.app_label, model._meta.module_name), ()) if is_concretely_inherited: ignored_model_perms += tuple( '{}_{}'.format(action, model._meta.module_name) for action in ('add', 'change', 'delete')) return [perm for perm in Permission.objects.filter(content_type=ct) if (perm.codename, perm.name) in auto_model_perms and perm.codename not in ignored_model_perms]
def create_permissions(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs): """Create permissions on django 1.10+.""" if not app_config.models_module: return try: ContentType = apps.get_model('contenttypes', 'ContentType') Permission = apps.get_model('auth', 'Permission') except LookupError: return if not router.allow_migrate_model(using, Permission): return searched_perms = list() # (content_type, (codename, name)) ctypes = set() # The codenames and ctypes that should exist. for klass in app_config.get_models(): ctype = ContentType.objects.db_manager(using).get_for_model(klass) ctypes.add(ctype) from django.contrib.auth.management import _get_all_permissions for perm in _get_all_permissions(klass._meta): searched_perms.append((ctype, perm)) all_perms = set(Permission.objects.using(using).filter( content_type__in=ctypes, ).values_list( "content_type", "codename" )) perms = [ Permission(codename=codename, name=name, content_type=ct) for ct, (codename, name) in searched_perms if (ct.pk, codename) not in all_perms ] Permission.objects.using(using).bulk_create(perms) if verbosity >= 2: for perm in perms: print("Adding permission '%s'" % perm)
def create_proxy_permissions(app, created_models, verbosity, **kwargs): import pdb; pdb.set_trace() kwargs.pop("interactive",None) update_contenttypes(app, created_models, verbosity, **kwargs) app_models = django.db.models.get_models(app) # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = list() # The codenames and ctypes that should exist. ctypes = set() for model in app_models: opts = model._meta if opts.proxy: # We can't use `get_for_model` here since it doesn't return # the correct `ContentType` for proxy models. # see https://code.djangoproject.com/ticket/17648 app_label, model = opts.app_label, opts.object_name.lower() ctype = ContentType.objects.get_by_natural_key(app_label, model) ctypes.add(ctype) for perm in _get_all_permissions(opts, ctypes): searched_perms.append((ctype, perm)) # Find all the Permissions that have a content_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_perms = set(Permission.objects.filter( content_type__in=ctypes, ).values_list( "content_type", "codename" )) objs = [ Permission(codename=codename, name=name, content_type=ctype) for ctype, (codename, name) in searched_perms if (ctype.pk, codename) not in all_perms ] Permission.objects.bulk_create(objs) if verbosity >= 2: for obj in objs: sys.stdout.write("Adding permission '%s'" % obj)
def _get_project_specific_permissions(model, is_concretely_inherited=False): from editorsnotes.auth.models import ProjectPermissionsMixin # Only deal with models which subclass ProjectPermissionsMixin if not issubclass(model, ProjectPermissionsMixin): return [] ct = ContentType.objects.get_for_model(model) auto_model_perms = _get_all_permissions(model._meta, ct) ignored_model_perms = IGNORED_PERMISSIONS.get( '{}.{}'.format(model._meta.app_label, model._meta.model_name), ()) if is_concretely_inherited: ignored_model_perms += tuple( '{}_{}'.format(action, model._meta.model_name) for action in ('add', 'change', 'delete')) return [ perm for perm in Permission.objects.filter(content_type=ct) if (perm.codename, perm.name) in auto_model_perms and perm.codename not in ignored_model_perms ]
def create_permissions_respecting_proxy( app, created_models, verbosity, **kwargs ): if not kwargs['sender'].__name__ == 'myproject.myapp.models': # if not in 'customer' app, then use the original function create_permissions(app, created_models, verbosity, **kwargs) return from django.contrib.contenttypes.models import ContentType from django.contrib.auth import models as auth_app app_models = get_models(app) searched_perms = list() ctypes = set() for klass in app_models: # this is where the difference is: the original create_permissions # use ctype = ContentType.objects.get_for_model(klass) opts = klass._meta ctype = ContentType.objects.get_or_create( app_label=opts.app_label, model=opts.object_name.lower(), defaults = {'name': smart_unicode(opts.verbose_name_raw)} ) # end of the modification ctypes.add(ctype) for perm in _get_all_permissions(klass._meta): searched_perms.append((ctype, perm)) all_perms = set(auth_app.Permission.objects.filter( content_type__in=ctypes ).values_list("content_type", "codename")) for ctype, (codename, name) in searched_perms: if(ctype.pk, codename) in all_perms: continue p = auth_app.Permission.objects.create( codename=codename, name=name, content_type=ctype ) if verbosity >=2: print "Adding permission '%s'" % p
def handle(self, *args, **options): if options['apps']: app_names = options['apps'].split(',') apps = [django_apps.get_app_config(x) for x in app_names] else: apps = django_apps.get_app_configs() if options['create_only']: do_create, do_update = True, False elif options['update_only']: do_create, do_update = False, True else: do_create, do_update = True, True for app in apps: if do_create: # create permissions if they do not exist create_permissions(app, options['verbosity']) if do_update: # update permission name's if changed for model in app.get_models(): content_type = ContentType.objects.get_for_model(model) for codename, name in _get_all_permissions(model._meta): try: permission = Permission.objects.get( codename=codename, content_type=content_type) except Permission.DoesNotExist: continue if permission.name != name: old_str = str(permission) permission.name = name if options['verbosity'] >= 2: self.stdout.write( self.style.SUCCESS( "Update permission '%s' to '%s'" % (old_str, permission))) permission.save()
def new_create_permissions(app, created_models, verbosity, db=DEFAULT_DB_ALIAS, **kwargs): if not router.allow_syncdb(db, auth_app.Permission): return from django.contrib.contenttypes.models import ContentType app_models = get_models(app) # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = list() # The codenames and ctypes that should exist. ctypes = set() ctypes_for_models = ContentType.objects.get_for_models(*app_models, for_concrete_models=False) for klass, ctype in ctypes_for_models.items(): ctypes.add(ctype) for perm in _get_all_permissions(klass._meta, ctype): searched_perms.append((ctype, perm)) # Find all the Permissions that have a context_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_perms = set(auth_app.Permission.objects.using(db).filter( content_type__in=ctypes, ).values_list( "content_type", "codename" )) perms = [ auth_app.Permission(codename=codename, name=name, content_type=ctype) for ctype, (codename, name) in searched_perms if (ctype.pk, codename) not in all_perms ] auth_app.Permission.objects.using(db).bulk_create(perms) if verbosity >= 2: for perm in perms: print("Adding permission '%s'" % perm)
def create_proxy_permissions( app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs): if not app_config.models_module: return logger = logging.getLogger(__name__) # print(app_config) try: logger.info("Tentando obter modelo de permissão do app.") Permission = django.apps.apps.get_model('auth', 'Permission') except LookupError as e: logger.error(str(e)) return if not router.allow_migrate_model(using, Permission): return from django.contrib.contenttypes.models import ContentType permission_name_max_length = Permission._meta.get_field('name').max_length # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = list() # The codenames and ctypes that should exist. ctypes = set() for klass in list(app_config.get_models()): opts = klass._meta permissions = ( ("list_" + opts.model_name, string_concat( _('Visualizaçao da lista de'), ' ', opts.verbose_name_plural)), ("detail_" + opts.model_name, string_concat( _('Visualização dos detalhes de'), ' ', opts.verbose_name_plural)), ) opts.permissions = tuple( set(list(permissions) + list(opts.permissions))) if opts.proxy: # Force looking up the content types in the current database # before creating foreign keys to them. app_label, model = opts.app_label, opts.model_name try: logger.info("Tentando obter db_manager.") ctype = ContentType.objects.db_manager( using).get_by_natural_key(app_label, model) except Exception as e: logger.error(str(e)) ctype = ContentType.objects.db_manager( using).create(app_label=app_label, model=model) else: ctype = ContentType.objects.db_manager(using).get_for_model(klass) ctypes.add(ctype) _all_perms_of_klass = _get_all_permissions(klass._meta) for perm in _all_perms_of_klass: searched_perms.append((ctype, perm)) # Find all the Permissions that have a content_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_perms = set(Permission.objects.using(using).filter( content_type__in=ctypes, ).values_list( "content_type", "codename" )) perms = [ Permission(codename=codename, name=name, content_type=ct) for ct, (codename, name) in searched_perms if (ct.pk, codename) not in all_perms ] # Validate the permissions before bulk_creation to avoid cryptic database # error when the name is longer than 255 characters for perm in perms: if len(perm.name) > permission_name_max_length: logger.error("The permission name %s of %s.%s " "is longer than %s characters" % ( perm.name, perm.content_type.app_label, perm.content_type.model, permission_name_max_length, )) raise exceptions.ValidationError( 'The permission name %s of %s.%s ' 'is longer than %s characters' % ( perm.name, perm.content_type.app_label, perm.content_type.model, permission_name_max_length, ) ) Permission.objects.using(using).bulk_create(perms) if verbosity >= 2: for perm in perms: print("Adding permission '%s'" % perm)
def __get_all_permissions(options, ctype): # django 1.10 compatibility if StrictVersion(get_version()) < StrictVersion('1.10'): return _get_all_permissions(options, ctype) return _get_all_permissions(options)
def create_proxy_permissions(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs): if not app_config.models_module: return try: Permission = apps.get_model('auth', 'Permission') except LookupError: return if not router.allow_migrate_model(using, Permission): return from django.contrib.contenttypes.models import ContentType permission_name_max_length = Permission._meta.get_field('name').max_length # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = list() # The codenames and ctypes that should exist. ctypes = set() for klass in app_config.get_models(): opts = klass._meta if opts.proxy: # Force looking up the content types in the current database # before creating foreign keys to them. app_label, model = opts.app_label, opts.model_name try: ctype = ContentType.objects.db_manager( using).get_by_natural_key(app_label, model) except: ctype = ContentType.objects.db_manager(using).create( app_label=app_label, model=model) else: ctype = ContentType.objects.db_manager(using).get_for_model(klass) ctypes.add(ctype) for perm in _get_all_permissions(klass._meta, ctype): searched_perms.append((ctype, perm)) # Find all the Permissions that have a content_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_perms = set( Permission.objects.using(using).filter( content_type__in=ctypes, ).values_list("content_type", "codename")) perms = [ Permission(codename=codename, name=name, content_type=ct) for ct, (codename, name) in searched_perms if (ct.pk, codename) not in all_perms ] # Validate the permissions before bulk_creation to avoid cryptic database # error when the name is longer than 255 characters for perm in perms: if len(perm.name) > permission_name_max_length: raise exceptions.ValidationError('The permission name %s of %s.%s ' 'is longer than %s characters' % ( perm.name, perm.content_type.app_label, perm.content_type.model, permission_name_max_length, )) Permission.objects.using(using).bulk_create(perms) if verbosity >= 2: for perm in perms: print("Adding permission '%s'" % perm)
def custom_create_permissions(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, apps=global_apps, **kwargs): # Getting models to exclude from permissions try: exclude = settings.UNRECOGNIZED_PERMISSION.get(app_config.label) except AttributeError: exclude = None if exclude is not None and exclude.count("all") != 0: return if not app_config.models_module: return app_label = app_config.label try: app_config = apps.get_app_config(app_label) ContentType = apps.get_model('contenttypes', 'ContentType') Permission = apps.get_model('auth', 'Permission') except LookupError: return if not router.allow_migrate_model(using, Permission): return # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = [] # The codenames and ctypes that should exist. ctypes = set() for klass in app_config.get_models(): # Force looking up the content types in the current database # before creating foreign keys to them. ctype = ContentType.objects.db_manager(using).get_for_model(klass) # Excluding unrecognized models if exclude is None or ctype.model not in exclude: ctypes.add(ctype) for perm in _get_all_permissions(klass._meta): searched_perms.append((ctype, perm)) # Find all the Permissions that have a content_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_perms = set( Permission.objects.using(using).filter( content_type__in=ctypes, ).values_list("content_type", "codename")) perms = [ Permission(codename=codename, name=name, content_type=ct) for ct, (codename, name) in searched_perms if (ct.pk, codename) not in all_perms ] Permission.objects.using(using).bulk_create(perms) if verbosity >= 2: for perm in perms: print("Adding permission '%s'" % perm)
def get_all_permissions(opts, ctype=None): if django_version() < DjangoVersion.DJANGO_110: return _get_all_permissions(opts, ctype) return _get_all_permissions(opts)
def create_proxy_permissions(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs): if not app_config.models_module: return # print(app_config) try: Permission = apps.get_model('auth', 'Permission') except LookupError: return if not router.allow_migrate_model(using, Permission): return from django.contrib.contenttypes.models import ContentType permission_name_max_length = Permission._meta.get_field('name').max_length # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = list() # The codenames and ctypes that should exist. ctypes = set() for klass in list(app_config.get_models()): opts = klass._meta permissions = ( ("list_" + opts.model_name, string_concat(_('Visualizaçao da lista de'), ' ', opts.verbose_name_plural)), ("detail_" + opts.model_name, string_concat(_('Visualização dos detalhes de'), ' ', opts.verbose_name_plural)), ) opts.permissions = tuple( set(list(permissions) + list(opts.permissions))) if opts.proxy: # Force looking up the content types in the current database # before creating foreign keys to them. app_label, model = opts.app_label, opts.model_name try: ctype = ContentType.objects.db_manager( using).get_by_natural_key(app_label, model) except: ctype = ContentType.objects.db_manager(using).create( app_label=app_label, model=model) else: ctype = ContentType.objects.db_manager(using).get_for_model(klass) ctypes.add(ctype) # FIXME: Retirar try except quando sapl passar a usar django 1.11 try: # Função não existe mais em Django 1.11 # como sapl ainda não foi para Django 1.11 # esta excessão foi adicionada para caso o # Sapl esteja rodando em um projeto 1.11 não ocorra erros _all_perms_of_klass = _get_all_permissions(klass._meta, ctype) except: # Nova função usada em projetos com Django 1.11 e o sapl é uma app _all_perms_of_klass = _get_all_permissions(klass._meta) for perm in _all_perms_of_klass: searched_perms.append((ctype, perm)) # Find all the Permissions that have a content_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_perms = set( Permission.objects.using(using).filter( content_type__in=ctypes, ).values_list("content_type", "codename")) perms = [ Permission(codename=codename, name=name, content_type=ct) for ct, (codename, name) in searched_perms if (ct.pk, codename) not in all_perms ] # Validate the permissions before bulk_creation to avoid cryptic database # error when the name is longer than 255 characters for perm in perms: if len(perm.name) > permission_name_max_length: raise exceptions.ValidationError('The permission name %s of %s.%s ' 'is longer than %s characters' % ( perm.name, perm.content_type.app_label, perm.content_type.model, permission_name_max_length, )) Permission.objects.using(using).bulk_create(perms) if verbosity >= 2: for perm in perms: print("Adding permission '%s'" % perm)
def create_proxy_permissions( app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs): if not app_config.models_module: return try: Permission = apps.get_model('auth', 'Permission') except LookupError: return if not router.allow_migrate_model(using, Permission): return from django.contrib.contenttypes.models import ContentType permission_name_max_length = Permission._meta.get_field('name').max_length # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = list() # The codenames and ctypes that should exist. ctypes = set() for klass in app_config.get_models(): opts = klass._meta if opts.proxy: # Force looking up the content types in the current database # before creating foreign keys to them. app_label, model = opts.app_label, opts.model_name try: ctype = ContentType.objects.db_manager( using).get_by_natural_key(app_label, model) except: ctype = ContentType.objects.db_manager( using).create(app_label=app_label, model=model) else: ctype = ContentType.objects.db_manager(using).get_for_model(klass) ctypes.add(ctype) for perm in _get_all_permissions(klass._meta, ctype): searched_perms.append((ctype, perm)) # Find all the Permissions that have a content_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_perms = set(Permission.objects.using(using).filter( content_type__in=ctypes, ).values_list( "content_type", "codename" )) perms = [ Permission(codename=codename, name=name, content_type=ct) for ct, (codename, name) in searched_perms if (ct.pk, codename) not in all_perms ] # Validate the permissions before bulk_creation to avoid cryptic database # error when the name is longer than 255 characters for perm in perms: if len(perm.name) > permission_name_max_length: raise exceptions.ValidationError( 'The permission name %s of %s.%s ' 'is longer than %s characters' % ( perm.name, perm.content_type.app_label, perm.content_type.model, permission_name_max_length, ) ) Permission.objects.using(using).bulk_create(perms) if verbosity >= 2: for perm in perms: print("Adding permission '%s'" % perm)
def create_permissions(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs): """ Copy/paste from django/contrib/auth/management/__init__.py with small modifications (for_concrete_model, app_config.get_proxies). Create permissions for defined proxy models in apps module. """ from django.apps import apps if not app_config.models_module: return try: Permission = apps.get_model('auth', 'Permission') except LookupError: return if not router.allow_migrate_model(using, Permission): return from django.contrib.contenttypes.models import ContentType # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = list() # The codenames and ctypes that should exist. ctypes = set() for klass in app_config.get_models(): # Force looking up the content types in the current database # before creating foreign keys to them. ctype = ContentType.objects.db_manager(using).get_for_model( model=klass, for_concrete_model=False) if klass._meta.proxy: concrete_ctype = ContentType.objects.db_manager( using).get_for_model( # noqa model=klass, ) perms = Permission.objects.using(using).filter( content_type=concrete_ctype, codename__endswith=klass._meta.model_name) if perms: perms.update(content_type=ctype) ctypes.add(ctype) for perm in _get_all_permissions(klass._meta, ctype): searched_perms.append((ctype, perm)) # Find all the Permissions that have a content_type for a model we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_perms = set( Permission.objects.using(using).filter( content_type__in=ctypes, ).values_list("content_type", "codename")) perms = [ Permission(codename=codename, name=name, content_type=ct) for ct, (codename, name) in searched_perms if (ct.pk, codename) not in all_perms ] # Validate the permissions before bulk_creation to avoid cryptic # database error when the verbose_name is longer than 50 characters permission_name_max_length = Permission._meta.get_field('name').max_length verbose_name_max_length = permission_name_max_length - len('Can change ') for perm in perms: if len(perm.name) > permission_name_max_length: raise exceptions.ValidationError( "The verbose_name of %s.%s is longer than %s characters" % ( perm.content_type.app_label, perm.content_type.model, verbose_name_max_length, )) Permission.objects.using(using).bulk_create(perms) if verbosity >= 2: for perm in perms: print("Adding permission '%s'" % perm)
def handle(self, *args, **options): for model in apps.get_models(): opts = model._meta ctype, created = ContentType.objects.get_or_create( app_label=opts.app_label, model=opts.object_name.lower()) for codename, name in _get_all_permissions(opts): p, created = Permission.objects.get_or_create( codename=codename, content_type=ctype, defaults={'name': name}) if created: sys.stdout.write('Adding permission {}\n'.format(p)) # add application specific rights for app in Application.objects.all(): content_type = ContentType.objects.get_for_model(Application) Permission.objects.get_or_create( codename=Application.appPermissionCode + app.name, name= 'Can view application and related variables and versions for ' + app.name, content_type=content_type, ) # add 'Variable Users' group variable_users_group, created = Group.objects.get_or_create( name='Variable Users') # Add permissions to 'Variable Users' group ct = ContentType.objects.get_for_model( variableServer.models.Application, for_concrete_model=False) variable_users_group.permissions.add( *Permission.objects.filter(Q(codename='add_application') | Q(codename='change_application'), content_type=ct)) ct = ContentType.objects.get_for_model(variableServer.models.TestCase, for_concrete_model=False) variable_users_group.permissions.add( *Permission.objects.filter(Q(codename='add_testcase') | Q(codename='change_testcase'), content_type=ct)) ct = ContentType.objects.get_for_model( variableServer.models.TestEnvironment, for_concrete_model=False) variable_users_group.permissions.add( *Permission.objects.filter(Q(codename='add_testenvironment') | Q(codename='change_testenvironment'), content_type=ct)) ct = ContentType.objects.get_for_model(variableServer.models.Version, for_concrete_model=False) variable_users_group.permissions.add( *Permission.objects.filter(Q(codename='add_version') | Q(codename='change_version'), content_type=ct)) ct = ContentType.objects.get_for_model(variableServer.models.Variable, for_concrete_model=False) variable_users_group.permissions.add( *Permission.objects.filter(Q(codename='add_variable') | Q(codename='change_variable') | Q(codename='delete_variable') | Q(codename='see_protected_var'), content_type=ct)) # add 'Variable Users' group snapshot_users_group, created = Group.objects.get_or_create( name='Snapshot Users') # Add permissions to 'Snapshot Users' group ct = ContentType.objects.get_for_model( snapshotServer.models.ExcludeZone) snapshot_users_group.permissions.add( *Permission.objects.filter(Q(codename='add_excludezone') | Q(codename='change_excludezone') | Q(codename='delete_excludezone'), content_type=ct)) ct = ContentType.objects.get_for_model( snapshotServer.models.Snapshot) # for upload snapshot_users_group.permissions.add( *Permission.objects.filter(Q(codename='add_snapshot') | Q(codename='change_snapshot'), content_type=ct)) ct = ContentType.objects.get_for_model( snapshotServer.models.TestCaseInSession) snapshot_users_group.permissions.add( *Permission.objects.filter(Q(codename='add_testcaseinsession') | Q( codename='change_testcaseinsession'), content_type=ct)) ct = ContentType.objects.get_for_model( snapshotServer.models.StepResult) snapshot_users_group.permissions.add( *Permission.objects.filter(Q(codename='add_stepresult') | Q(codename='change_stepresult'), content_type=ct)) ct = ContentType.objects.get_for_model( snapshotServer.models.TestSession) snapshot_users_group.permissions.add( *Permission.objects.filter(Q(codename='add_testsession') | Q(codename='change_testsession'), content_type=ct)) ct = ContentType.objects.get_for_model(snapshotServer.models.TestStep) snapshot_users_group.permissions.add( *Permission.objects.filter(Q(codename='add_teststep') | Q(codename='change_teststep'), content_type=ct)) print("Groups and permissions added")
def update_ctypes_permissions(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs): """ Creates resources content types and default permissions. Most bits taken from contenttypes.management.update_contenttypes and auth.management.create_permissions. This will not make any attempt to clear content types no longer associated to resources. Note: ----- Because content types will not remain associated with real models, Django will ask to remove them after every migration. Although this function will recreate them, model instances with non-weak relations to them will be also deleted by the cascade, so for the time being is better to say "no" asked to remove stale content types. TODO: This *may* be addressed/mitigated defining a database router with a defined allow_migrate() method that checks the app against ContentType; e.g.: def allow_migrate(self, db, app_label, model_name=None, **hints): if <this app_label comes from a restorm app>: # don't allow the migration # (although maybe it's worth checking mode_name) return False # no opinion (let other routers decide) return None see docs.djangoproject.com/en/1.8/topics/db/multi-db/#allow_migrate """ if not isinstance(app_config, RestormAppConfig): # Any model will end up here, we are only interested in # restorm resources. return if not app_config.models_module: # This is left here for compatibility with Django. # Works because restorm resources are defined in the models.py. return try: ContentType = apps.get_model('contenttypes', 'ContentType') Permission = apps.get_model('auth', 'Permission') except LookupError: return if not router.allow_migrate_model(using, ContentType) \ or not router.allow_migrate_model(using, Permission): return ContentType.objects.clear_cache() app_label = app_config.label app_resources = { resource._meta.resource_name: resource for resource in app_config.get_resources() } if not app_resources: return # Get all the content types for this app content_types = { ct.model: ct for ct in ContentType.objects.using(using).filter(app_label=app_label) } # Create in memory any missing content type cts = [ ContentType(app_label=app_label, model=resources_name) for (resources_name, resource) in six.iteritems(app_resources) if resources_name not in content_types ] # Bulk-create the new instances ContentType.objects.using(using).bulk_create(cts) if verbosity >= 2: msg = "Adding content type '{0.app_label} | {0.model}' (restorm)".format for ct in cts: print(msg(ct)) # This will hold the permissions we're looking for as # (content_type, (codename, name)) searched_perms = list() # The codenames and ctypes that should exist. ctypes = set() for klass in app_resources.values(): # Force looking up the content types in the current database # before creating foreign keys to them. ctype = ContentType.objects.db_manager(using).get_for_model(klass) ctypes.add(ctype) for perm in _get_all_permissions(klass._meta, ctype): searched_perms.append((ctype, perm)) # Find all the Permissions that have a content_type for a resource we're # looking for. We don't need to check for codenames since we already have # a list of the ones we're going to create. all_perms = set( Permission.objects.using(using).filter( content_type__in=ctypes, ).values_list("content_type", "codename")) perms = [ Permission(codename=codename, name=name, content_type=ct) for ct, (codename, name) in searched_perms if (ct.pk, codename) not in all_perms ] # Validate the permissions before bulk_creation to avoid cryptic # database error when the verbose_name is longer than 50 characters. permission_name_max_length = Permission._meta.get_field('name').max_length verbose_name_max_length = permission_name_max_length - 11 # len('Can change ') prefix for perm in perms: if len(perm.name) > permission_name_max_length: raise exceptions.ValidationError( "The verbose_name of %s.%s is longer than %s characters" % ( perm.content_type.app_label, perm.content_type.model, verbose_name_max_length, )) Permission.objects.using(using).bulk_create(perms) if verbosity >= 2: for perm in perms: print("Adding permission '%s' (restorm)" % perm)
def fix_proxy_permissions(sender, **kwargs): """ `post_migrate` signal handler that copies permissions from the concrete models to the proxy models if any. """ if not is_perms_app(sender): return perms_counts = dict(perms=[], count=0) total_counts = dict(perms=[], concrete_models=[], proxy_models=[]) stats = dict(total=total_counts, concrete_deleted=perms_counts.copy(), proxy_added=perms_counts.copy()) for model in apps.get_models(): opts = model._meta if not opts.proxy: stats['total']['concrete_models'].append(opts) continue # The content_type creation is needed for the tests proxy_content_type, __ = ContentType.objects.get_or_create( app_label=opts.app_label, model=opts.model_name, ) concrete_content_type = ContentType.objects.get_for_model( model, for_concrete_model=True, ) all_model_perms = _get_all_permissions(opts) stats['total']['proxy_models'].append(opts.label_lower) for codename, name in all_model_perms: # Delete the automatically generated permission from Django deleted, _rows_count = Permission.objects.filter( codename=codename, content_type=concrete_content_type, ).delete() if deleted: stats['concrete_deleted']['perms'].append(_rows_count) stats['concrete_deleted']['count'] += deleted # Create the correct permission for the proxy model perm, created = Permission.objects.get_or_create( codename=codename, content_type=proxy_content_type, defaults={ 'name': name, }) if created: stats['proxy_added']['perms'].append(perm.codename) stats['total']['perms'] = [ codename for codename, name in all_model_perms ] sys.stdout.write( 'fixed PROXY/CONCRETE/TOTAL=%s/%s/%s new msg7 permissions %s for: %s.\n' % ( len(stats['proxy_added']['perms']), len(stats['concrete_deleted']['perms']), len(stats['total']['perms']), stats['proxy_added']['perms'], stats['total']['proxy_models'], ))