Python django.apps.apps() Examples
The following are 30
code examples of django.apps.apps().
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.apps
, or try the search function
.
Example #1
Source File: apps.py From django-admin-view-permission with BSD 2-Clause "Simplified" License | 6 votes |
def update_permissions(sender, app_config, verbosity, apps=global_apps, **kwargs): settings_models = getattr(settings, 'ADMIN_VIEW_PERMISSION_MODELS', None) # TODO: Maybe look at the registry not in all models for app in apps.get_app_configs(): for model in app.get_models(): view_permission = 'view_%s' % model._meta.model_name if settings_models or (settings_models is not None and len( settings_models) == 0): model_name = get_model_name(model) if model_name in settings_models and view_permission not in \ [perm[0] for perm in model._meta.permissions]: model._meta.permissions += ( (view_permission, 'Can view %s' % model._meta.model_name),) else: if view_permission not in [perm[0] for perm in model._meta.permissions]: model._meta.permissions += ( ('view_%s' % model._meta.model_name, 'Can view %s' % model._meta.model_name),)
Example #2
Source File: test_foreignkey.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_abstract_model_pending_operations(self): """ Foreign key fields declared on abstract models should not add lazy relations to resolve relationship declared as string (#24215). """ pending_ops_before = list(apps._pending_operations.items()) class AbstractForeignKeyModel(models.Model): fk = models.ForeignKey('missing.FK', models.CASCADE) class Meta: abstract = True self.assertIs(AbstractForeignKeyModel._meta.apps, apps) self.assertEqual( pending_ops_before, list(apps._pending_operations.items()), 'Pending lookup added for a foreign key on an abstract model' )
Example #3
Source File: test_manytomanyfield.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_abstract_model_pending_operations(self): """ Many-to-many fields declared on abstract models should not add lazy relations to resolve relationship declared as string (#24215). """ pending_ops_before = list(apps._pending_operations.items()) class AbstractManyToManyModel(models.Model): fk = models.ForeignKey('missing.FK', models.CASCADE) class Meta: abstract = True self.assertIs(AbstractManyToManyModel._meta.apps, apps) self.assertEqual( pending_ops_before, list(apps._pending_operations.items()), 'Pending lookup added for a many-to-many field on an abstract model' )
Example #4
Source File: test_foreignkey.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_abstract_model_pending_operations(self): """ Foreign key fields declared on abstract models should not add lazy relations to resolve relationship declared as string (#24215). """ pending_ops_before = list(apps._pending_operations.items()) class AbstractForeignKeyModel(models.Model): fk = models.ForeignKey('missing.FK', models.CASCADE) class Meta: abstract = True self.assertIs(AbstractForeignKeyModel._meta.apps, apps) self.assertEqual( pending_ops_before, list(apps._pending_operations.items()), 'Pending lookup added for a foreign key on an abstract model' )
Example #5
Source File: test_manytomanyfield.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_abstract_model_pending_operations(self): """ Many-to-many fields declared on abstract models should not add lazy relations to resolve relationship declared as string (#24215). """ pending_ops_before = list(apps._pending_operations.items()) class AbstractManyToManyModel(models.Model): fk = models.ForeignKey('missing.FK', models.CASCADE) class Meta: abstract = True self.assertIs(AbstractManyToManyModel._meta.apps, apps) self.assertEqual( pending_ops_before, list(apps._pending_operations.items()), 'Pending lookup added for a many-to-many field on an abstract model' )
Example #6
Source File: tests.py From Spirit with MIT License | 6 votes |
def test_migration_11_idempotency(self): """Should be idempotent""" with override_settings(ST_CASE_INSENSITIVE_USERNAMES=False): utils.create_user(username='FOO') self.assertEqual( UserProfile.objects.all().update(nickname=''), 1) data_migration_11.populate_nickname(apps, None) data_migration_11.make_usernames_lower(apps, None) self.assertEqual( [u.username for u in User.objects.all()], ['foo']) self.assertEqual( [u.nickname for u in UserProfile.objects.all()], ['FOO']) data_migration_11.populate_nickname(apps, None) data_migration_11.make_usernames_lower(apps, None) self.assertEqual( [u.username for u in User.objects.all()], ['foo']) self.assertEqual( [u.nickname for u in UserProfile.objects.all()], ['FOO'])
Example #7
Source File: tests.py From Spirit with MIT License | 6 votes |
def test_migration_11_make_usernames_lower_integrity_err(self): with override_settings(ST_CASE_INSENSITIVE_USERNAMES=False): utils.create_user(username='FOO') utils.create_user(username='fOo') utils.create_user(username='Foo') utils.create_user(username='bar') utils.create_user(username='bAr') utils.create_user(username='baz') self.assertEqual( [u.username for u in User.objects.all()], ['FOO', 'fOo', 'Foo', 'bar', 'bAr', 'baz']) # transaction is already handled with self.assertRaises(IntegrityError) as cm: data_migration_11.make_usernames_lower(apps, None) self.maxDiff = None self.assertEqual( str(cm.exception), "There are two or more users with similar name but " "different casing, for example: someUser and SomeUser, " "either remove one of them or set the " "`ST_CASE_INSENSITIVE_USERNAMES` setting to False. " "Then run the upgrade/migration again. Any change was reverted. " "Duplicate users are ['FOO', 'fOo', 'Foo', 'bar', 'bAr']")
Example #8
Source File: tests.py From Spirit with MIT License | 6 votes |
def test_migration_11_no_ci_usernames(self): utils.create_user(username='FOO') utils.create_user(username='foo') utils.create_user(username='BaR') utils.create_user(username='bar') utils.create_user(username='baz') self.assertEqual( UserProfile.objects.all().update(nickname=''), 5) data_migration_11.populate_nickname(apps, None) self.assertEqual( [u.nickname for u in UserProfile.objects.all()], ['FOO', 'foo', 'BaR', 'bar', 'baz']) self.assertEqual( [u.username for u in User.objects.all()], ['FOO', 'foo', 'BaR', 'bar', 'baz']) data_migration_11.make_usernames_lower(apps, None) self.assertEqual( [u.username for u in User.objects.all()], ['FOO', 'foo', 'BaR', 'bar', 'baz']) self.assertEqual( [u.nickname for u in UserProfile.objects.all()], ['FOO', 'foo', 'BaR', 'bar', 'baz'])
Example #9
Source File: tests.py From Spirit with MIT License | 6 votes |
def test_migration_11(self): # create users with the CI feature off # to replicate pre feature database state with override_settings(ST_CASE_INSENSITIVE_USERNAMES=False): utils.create_user(username='FOO') utils.create_user(username='BaR') utils.create_user(username='baz') # default all nicknames to empty self.assertEqual( UserProfile.objects.all().update(nickname=''), 3) data_migration_11.populate_nickname(apps, None) self.assertEqual( [u.nickname for u in UserProfile.objects.all()], ['FOO', 'BaR', 'baz']) self.assertEqual( [u.username for u in User.objects.all()], ['FOO', 'BaR', 'baz']) data_migration_11.make_usernames_lower(apps, None) self.assertEqual( [u.username for u in User.objects.all()], ['foo', 'bar', 'baz']) self.assertEqual( [u.nickname for u in UserProfile.objects.all()], ['FOO', 'BaR', 'baz'])
Example #10
Source File: migrations.py From django-postgres-extra with MIT License | 6 votes |
def add_field(field, filters: List[str]): """Adds the specified field to a model. Arguments: field: The field to add to a model. filters: List of strings to filter SQL statements on. """ model = define_fake_model() state = migrations.state.ProjectState.from_apps(apps) apply_migration([migrations.CreateModel(model.__name__, fields=[])], state) with filtered_schema_editor(*filters) as calls: apply_migration( [migrations.AddField(model.__name__, "title", field)], state ) yield calls
Example #11
Source File: test_middleware.py From django-request-profiler with MIT License | 6 votes |
def test_for_missing_migrations(self): """Checks if there're models changes which aren't reflected in migrations.""" migrations_loader = MigrationExecutor(connection).loader migrations_detector = MigrationAutodetector( from_state=migrations_loader.project_state(), to_state=ProjectState.from_apps(apps), ) if migrations_detector.changes(graph=migrations_loader.graph): self.fail( "Your models have changes that are not yet reflected " "in a migration. You should add them now." )
Example #12
Source File: has_missing_migrations.py From django-react-boilerplate with MIT License | 6 votes |
def handle(self, *args, **options): changed = set() self.stdout.write("Checking...") for db in settings.DATABASES.keys(): try: executor = MigrationExecutor(connections[db]) except OperationalError: sys.exit("Unable to check migrations: cannot connect to database\n") autodetector = MigrationAutodetector( executor.loader.project_state(), ProjectState.from_apps(apps), ) changed.update(autodetector.changes(graph=executor.loader.graph).keys()) changed -= set(options["ignore"]) if changed: sys.exit( "Apps with model changes but no corresponding migration file: %(changed)s\n" % {"changed": list(changed)} ) else: sys.stdout.write("All migration files present\n")
Example #13
Source File: migrations.py From django-postgres-extra with MIT License | 5 votes |
def alter_field(old_field, new_field, filters: List[str]): """Alters a field from one state to the other. Arguments: old_field: The field before altering it. new_field: The field after altering it. filters: List of strings to filter SQL statements on. """ model = define_fake_model({"title": old_field}) state = migrations.state.ProjectState.from_apps(apps) apply_migration( [ migrations.CreateModel( model.__name__, fields=[("title", old_field.clone())] ) ], state, ) with filtered_schema_editor(*filters) as calls: apply_migration( [migrations.AlterField(model.__name__, "title", new_field)], state ) yield calls
Example #14
Source File: migrations.py From django-postgres-extra with MIT License | 5 votes |
def rename_field(field, filters: List[str]): """Renames a field from one name to the other. Arguments: field: Field to be renamed. filters: List of strings to filter SQL statements on. """ model = define_fake_model({"title": field}) state = migrations.state.ProjectState.from_apps(apps) apply_migration( [ migrations.CreateModel( model.__name__, fields=[("title", field.clone())] ) ], state, ) with filtered_schema_editor(*filters) as calls: apply_migration( [migrations.RenameField(model.__name__, "title", "newtitle")], state ) yield calls
Example #15
Source File: migrations.py From django-postgres-extra with MIT License | 5 votes |
def alter_db_table(field, filters: List[str]): """Creates a model with the specified field and then renames the database table. Arguments: field: The field to include into the model. filters: List of strings to filter SQL statements on. """ model = define_fake_model() state = migrations.state.ProjectState.from_apps(apps) apply_migration( [ migrations.CreateModel( model.__name__, fields=[("title", field.clone())] ) ], state, ) with filtered_schema_editor(*filters) as calls: apply_migration( [migrations.AlterModelTable(model.__name__, "NewTableName")], state ) yield calls
Example #16
Source File: migrations.py From django-postgres-extra with MIT License | 5 votes |
def make_migration(app_label="tests", from_state=None, to_state=None): """Generates migrations based on the specified app's state.""" app_labels = [app_label] loader = MigrationLoader(None, ignore_no_migrations=True) loader.check_consistent_history(connection) questioner = NonInteractiveMigrationQuestioner( specified_apps=app_labels, dry_run=False ) autodetector = MigrationAutodetector( from_state or loader.project_state(), to_state or ProjectState.from_apps(apps), questioner, ) changes = autodetector.changes( graph=loader.graph, trim_to_apps=app_labels or None, convert_apps=app_labels or None, migration_name="test", ) changes_for_app = changes.get(app_label) if not changes_for_app or len(changes_for_app) == 0: return None return changes_for_app[0]
Example #17
Source File: migrations.py From django-postgres-extra with MIT License | 5 votes |
def apply_migration(operations, state=None, backwards: bool = False): """Executes the specified migration operations using the specified schema editor. Arguments: operations: The migration operations to execute. state: The state state to use during the migrations. backwards: Whether to apply the operations in reverse (backwards). """ state = state or migrations.state.ProjectState.from_apps(apps) class Migration(migrations.Migration): pass Migration.operations = operations migration = Migration("migration", "tests") executor = MigrationExecutor(connection) if not backwards: executor.apply_migration(state, migration) else: executor.unapply_migration(state, migration) return migration
Example #18
Source File: test_partitioned_model_state.py From django-postgres-extra with MIT License | 5 votes |
def test_partitioned_model_render(model): """Tests whether the state can be rendered into a valid model class.""" options = dict(method=PostgresPartitioningMethod.RANGE, key=["timestamp"]) state = PostgresPartitionedModelState( app_label="tests", name=str(uuid.uuid4()), fields=[("name", models.TextField())], options=None, partitioning_options=options, bases=(PostgresPartitionedModel,), managers=[("cookie", PostgresManager())], ) rendered_model = state.render(apps) assert issubclass(rendered_model, PostgresPartitionedModel) assert rendered_model.name assert isinstance(rendered_model.objects, PostgresManager) assert isinstance(rendered_model.cookie, PostgresManager) assert rendered_model.__name__ == state.name assert rendered_model._meta.apps == apps assert rendered_model._meta.app_label == "tests" assert rendered_model._partitioning_meta.method == options["method"] assert rendered_model._partitioning_meta.key == options["key"]
Example #19
Source File: test_migrations.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_migrate_backwards(self): update_proxy_permissions.update_proxy_model_permissions(apps, None) update_proxy_permissions.revert_proxy_model_permissions(apps, None) self.default_permission.refresh_from_db() self.assertEqual(self.default_permission.content_type, self.concrete_content_type) self.custom_permission.refresh_from_db() self.assertEqual(self.custom_permission.content_type, self.concrete_content_type)
Example #20
Source File: test_migration_operations.py From django-postgres-extra with MIT License | 5 votes |
def test_migration_operations_create_partitioned_table(method, create_model): """Tests whether the see :PostgresCreatePartitionedModel operation works as expected in a migration.""" create_operation = create_model(method) state = migrations.state.ProjectState.from_apps(apps) # migrate forwards, is the table there? apply_migration([create_operation], state) assert _partitioned_table_exists(create_operation) # migrate backwards, is the table there? apply_migration([create_operation], state=state, backwards=True) assert not _partitioned_table_exists(create_operation)
Example #21
Source File: test_migration_operations.py From django-postgres-extra with MIT License | 5 votes |
def test_migration_operations_delete_partitioned_table(method, create_model): """Tests whether the see :PostgresDeletePartitionedModel operation works as expected in a migration.""" create_operation = create_model(method) delete_operation = operations.PostgresDeletePartitionedModel( create_operation.name ) state = migrations.state.ProjectState.from_apps(apps) # migrate forwards, create model apply_migration([create_operation], state) assert _partitioned_table_exists(create_operation) # record intermediate state, the state we'll # migrate backwards to intm_state = state.clone() # migrate forwards, delete model apply_migration([delete_operation], state) assert not _partitioned_table_exists(create_operation) # migrate backwards, undelete model delete_operation.database_backwards( "tests", connection.schema_editor(), state, intm_state ) assert _partitioned_table_exists(create_operation)
Example #22
Source File: test_migration_operations.py From django-postgres-extra with MIT License | 5 votes |
def test_migration_operations_add_delete_partition( method, add_partition_operation, delete_partition_operation, create_model ): """Tests whether adding partitions and then removing them works as expected.""" create_operation = create_model(method) state = migrations.state.ProjectState.from_apps(apps) # migrate forwards, create model and partition apply_migration([create_operation, add_partition_operation], state) assert _partition_exists(create_operation, add_partition_operation) # record intermediate state, the state we'll # migrate backwards to intm_state = state.clone() # migrate forwards, delete the partition apply_migration([delete_partition_operation], state) assert not _partition_exists(create_operation, add_partition_operation) # migrate backwards, undelete the partition delete_partition_operation.database_backwards( "tests", connection.schema_editor(), state, intm_state ) assert _partition_exists(create_operation, add_partition_operation)
Example #23
Source File: test_migrations.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_user_still_has_proxy_model_permissions(self): user = User.objects.create() user.user_permissions.add(self.default_permission) user.user_permissions.add(self.custom_permission) for permission in [self.default_permission, self.custom_permission]: self.assertTrue(user.has_perm('auth_tests.' + permission.codename)) update_proxy_permissions.update_proxy_model_permissions(apps, None) # Reload user to purge the _perm_cache. user = User._default_manager.get(pk=user.pk) for permission in [self.default_permission, self.custom_permission]: self.assertTrue(user.has_perm('auth_tests.' + permission.codename))
Example #24
Source File: test_migrations.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_proxy_model_permissions_contenttype(self): proxy_model_content_type = ContentType.objects.get_for_model(Proxy, for_concrete_model=False) self.assertEqual(self.default_permission.content_type, self.concrete_content_type) self.assertEqual(self.custom_permission.content_type, self.concrete_content_type) update_proxy_permissions.update_proxy_model_permissions(apps, None) self.default_permission.refresh_from_db() self.custom_permission.refresh_from_db() self.assertEqual(self.default_permission.content_type, proxy_model_content_type) self.assertEqual(self.custom_permission.content_type, proxy_model_content_type)
Example #25
Source File: test_migrations.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_user_keeps_same_permissions_after_migrating_backward(self): user = User.objects.create() user.user_permissions.add(self.default_permission) user.user_permissions.add(self.custom_permission) for permission in [self.default_permission, self.custom_permission]: self.assertTrue(user.has_perm('auth.' + permission.codename)) self.assertFalse(user.has_perm('auth_tests.' + permission.codename)) update_proxy_permissions.update_proxy_model_permissions(apps, None) update_proxy_permissions.revert_proxy_model_permissions(apps, None) # Reload user to purge the _perm_cache. user = User._default_manager.get(pk=user.pk) for permission in [self.default_permission, self.custom_permission]: self.assertTrue(user.has_perm('auth.' + permission.codename)) self.assertFalse(user.has_perm('auth_tests.' + permission.codename))
Example #26
Source File: test_migrations.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_migrate_backwards(self): update_proxy_permissions.update_proxy_model_permissions(apps, None) update_proxy_permissions.revert_proxy_model_permissions(apps, None) self.default_permission.refresh_from_db() self.assertEqual(self.default_permission.content_type, self.concrete_content_type) self.custom_permission.refresh_from_db() self.assertEqual(self.custom_permission.content_type, self.concrete_content_type)
Example #27
Source File: test_migrations.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_proxy_model_permissions_contenttype(self): proxy_model_content_type = ContentType.objects.get_for_model(UserProxy, for_concrete_model=False) self.assertEqual(self.default_permission.content_type, self.concrete_content_type) self.assertEqual(self.custom_permission.content_type, self.concrete_content_type) update_proxy_permissions.update_proxy_model_permissions(apps, None) self.default_permission.refresh_from_db() self.assertEqual(self.default_permission.content_type, proxy_model_content_type) self.custom_permission.refresh_from_db() self.assertEqual(self.custom_permission.content_type, proxy_model_content_type)
Example #28
Source File: 0053_twl_team_user.py From TWLight with MIT License | 5 votes |
def twl_team(apps, schema_editor): User.objects.get_or_create( username="TWL Team", email="wikipedialibrary@wikimedia.org" )
Example #29
Source File: test_migrations.py From django-request-token with MIT License | 5 votes |
def test_for_missing_migrations(self): """Checks if there're models changes which aren't reflected in migrations.""" migrations_loader = MigrationExecutor(connection).loader migrations_detector = MigrationAutodetector( from_state=migrations_loader.project_state(), to_state=ProjectState.from_apps(apps), ) if migrations_detector.changes(graph=migrations_loader.graph): self.fail( "Your models have changes that are not yet reflected " "in a migration. You should add them now." )
Example #30
Source File: test_migrations.py From elasticsearch-django with MIT License | 5 votes |
def test_for_missing_migrations(self): """Checks if there're models changes which aren't reflected in migrations.""" current_models_state = ProjectState.from_apps(apps) # skip tracking changes for TestModel current_models_state.remove_model("tests", "testmodel") migrations_loader = MigrationExecutor(connection).loader migrations_detector = MigrationAutodetector( from_state=migrations_loader.project_state(), to_state=current_models_state ) if migrations_detector.changes(graph=migrations_loader.graph): self.fail( "Your models have changes that are not yet reflected " "in a migration. You should add them now." )