Python django.apps.apps() Examples

The following are 30 code examples for showing how to use django.apps.apps(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.apps , or try the search function .

Example 1
Project: django-admin-view-permission   Author: ctxis   File: apps.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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
Project: django-react-boilerplate   Author: vintasoftware   File: has_missing_migrations.py    License: MIT License 6 votes vote down vote up
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 3
Project: Spirit   Author: nitely   File: tests.py    License: MIT License 6 votes vote down vote up
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 4
Project: Spirit   Author: nitely   File: tests.py    License: MIT License 6 votes vote down vote up
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 5
Project: Spirit   Author: nitely   File: tests.py    License: MIT License 6 votes vote down vote up
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 6
Project: Spirit   Author: nitely   File: tests.py    License: MIT License 6 votes vote down vote up
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
Project: djongo   Author: nesdis   File: test_manytomanyfield.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 8
Project: djongo   Author: nesdis   File: test_foreignkey.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 9
Project: djongo   Author: nesdis   File: test_manytomanyfield.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 10
Project: djongo   Author: nesdis   File: test_foreignkey.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 11
Project: django-postgres-extra   Author: SectorLabs   File: migrations.py    License: MIT License 6 votes vote down vote up
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 12
Project: lego   Author: webkom   File: missing_migrations.py    License: MIT License 5 votes vote down vote up
def run(self, *args, **kwargs):

        changed = set()

        log.info("Checking DB migrations")
        for db in settings.DATABASES.keys():

            try:
                executor = MigrationExecutor(connections[db])
            except OperationalError:
                log.critical("Unable to check migrations, cannot connect to database")
                sys.exit(1)

            autodetector = MigrationAutodetector(
                executor.loader.project_state(), ProjectState.from_apps(apps)
            )

            changed.update(autodetector.changes(graph=executor.loader.graph).keys())

        if changed:
            log.critical(
                "Apps with model changes but no corresponding "
                f"migration file: {list(changed)}"
            )
            sys.exit(1)
        else:
            log.info("All migration files present") 
Example 13
Project: django-react-boilerplate   Author: vintasoftware   File: has_missing_migrations.py    License: MIT License 5 votes vote down vote up
def add_arguments(self, parser):
        parser.add_argument(
            "--ignore",
            action="store",
            nargs="+",
            dest="ignore",
            default=[],
            help="Comma separated list of apps to ignore missing migration files. "
            "Useful for specifying third-party ones here.",
        ) 
Example 14
Project: django-package-monitor   Author: yunojuno-archive   File: test_migrations.py    License: MIT License 5 votes vote down vote up
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 15
Project: django-request-profiler   Author: yunojuno   File: test_middleware.py    License: MIT License 5 votes vote down vote up
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 16
Project: django-andablog   Author: WimpyAnalytics   File: check_missing_migrations.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def handle(self, *args, **kwargs):

        changed = set()
        ignore_list = ['authtools']  # dependencies that we don't care about migrations for (usually for testing only)

        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())

        for ignore in ignore_list:
            if ignore in changed:
                changed.remove(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 17
Project: Spirit   Author: nitely   File: tests.py    License: MIT License 5 votes vote down vote up
def test_migration_profiles(self):
        """Should create profile for existing users"""
        foo = utils.create_user(username='foo')
        bar = utils.create_user(username='bar')
        UserProfile.objects.filter(user=foo).delete()
        UserProfile.objects.filter(user=bar).delete()
        foo = User.objects.get(pk=foo.pk)
        bar = User.objects.get(pk=bar.pk)
        with self.assertRaises(ObjectDoesNotExist):
            self.assertIsNone(foo.st)
        with self.assertRaises(ObjectDoesNotExist):
            self.assertIsNone(bar.st)
        data_migration_profiles.migrate_profiles(apps, None)
        self.assertTrue(User.objects.get(pk=foo.pk).st.is_verified)
        self.assertTrue(User.objects.get(pk=bar.pk).st.is_verified) 
Example 18
Project: elasticsearch-django   Author: yunojuno   File: test_migrations.py    License: MIT License 5 votes vote down vote up
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."
            ) 
Example 19
Project: django-request-token   Author: yunojuno   File: test_migrations.py    License: MIT License 5 votes vote down vote up
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 20
Project: TWLight   Author: WikipediaLibrary   File: 0053_twl_team_user.py    License: MIT License 5 votes vote down vote up
def twl_team(apps, schema_editor):
    User.objects.get_or_create(
        username="TWL Team", email="wikipedialibrary@wikimedia.org"
    ) 
Example 21
Project: djongo   Author: nesdis   File: test_migrations.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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 22
Project: djongo   Author: nesdis   File: test_migrations.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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 23
Project: djongo   Author: nesdis   File: test_migrations.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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 24
Project: djongo   Author: nesdis   File: test_migrations.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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
Project: djongo   Author: nesdis   File: test_migrations.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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 26
Project: djongo   Author: nesdis   File: test_migrations.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
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
Project: django-postgres-extra   Author: SectorLabs   File: test_partitioned_model_state.py    License: MIT License 5 votes vote down vote up
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 28
Project: django-postgres-extra   Author: SectorLabs   File: migrations.py    License: MIT License 5 votes vote down vote up
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 29
Project: django-postgres-extra   Author: SectorLabs   File: migrations.py    License: MIT License 5 votes vote down vote up
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 30
Project: django-postgres-extra   Author: SectorLabs   File: migrations.py    License: MIT License 5 votes vote down vote up
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