Python django.apps() Examples

The following are 30 code examples for showing how to use django.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 , or try the search function .

Example 1
Project: django-cassandra-engine   Author: r4fek   File: utils.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_installed_apps():
    """
    Return list of all installed apps
    """
    if django.VERSION >= (1, 7):
        from django.apps import apps

        return [
            a.models_module
            for a in apps.get_app_configs()
            if a.models_module is not None
        ]
    else:
        from django.db import models

        return models.get_apps() 
Example 2
Project: django-cassandra-engine   Author: r4fek   File: tests.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_get_fields_only_searches_forward_on_apps_not_ready(self):
        opts = CassandraThing._meta
        # If apps registry is not ready, get_field() searches over only
        # forward fields.
        opts.apps.models_ready = False
        try:
            # 'data_abstract' is a forward field, and therefore will be found
            self.assertTrue(opts.get_field('data_abstract'))
            msg = (
                "CassandraThing has no field named 'relating_baseperson'. The app "
                "cache isn't ready yet, so if this is an auto-created related "
                "field, it won't be available yet."
            )
            # 'data_abstract' is a reverse field, and will raise an exception
            with self.assertRaisesMessage(FieldDoesNotExist, msg):
                opts.get_field('relating_baseperson')
        finally:
            opts.apps.models_ready = True 
Example 3
Project: django-ftpserver   Author: tokibito   File: conf.py    License: MIT License 6 votes vote down vote up
def setup_django():
    import django
    from django.conf import settings
    if not settings.configured:
        settings.configure(
            DEBUG=True,
            DATABASES={
                'default': {
                    'ENGINE': 'django.db.backends.sqlite3',
                    'NAME': ':memory:',
                }
            },
            INSTALLED_APPS=(
                'django.contrib.admin',
                'django.contrib.auth',
                'django.contrib.contenttypes',
                'django.contrib.sessions',
                'django.contrib.messages',
                'django_ftpserver',
            )
        )
    django.setup()
    from django.apps import apps
    if not apps.ready:
        apps.populate() 
Example 4
Project: django-ra-erp   Author: ra-systems   File: runtests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get_test_modules():
    modules = []
    discovery_paths = [(None, RUNTESTS_DIR)]
    if connection.features.gis_enabled:
        # GIS tests are in nested apps
        discovery_paths.append(('gis_tests', os.path.join(RUNTESTS_DIR, 'gis_tests')))
    else:
        SUBDIRS_TO_SKIP.append('gis_tests')

    for modpath, dirpath in discovery_paths:
        for f in os.scandir(dirpath):
            if ('.' not in f.name and
                    os.path.basename(f.name) not in SUBDIRS_TO_SKIP and
                    not f.is_file() and
                    os.path.exists(os.path.join(f.path, '__init__.py'))):
                modules.append((modpath, f.name))
    return modules 
Example 5
Project: django-mock-queries   Author: stphivos   File: mocks.py    License: MIT License 6 votes vote down vote up
def mock_django_setup(settings_module, disabled_features=None):
    """ Must be called *AT IMPORT TIME* to pretend that Django is set up.

    This is useful for running tests without using the Django test runner.
    This must be called before any Django models are imported, or they will
    complain. Call this from a module in the calling project at import time,
    then be sure to import that module at the start of all mock test modules.
    Another option is to call it from the test package's init file, so it runs
    before all the test modules are imported.
    :param settings_module: the module name of the Django settings file,
        like 'myapp.settings'
    :param disabled_features: a list of strings that should be marked as
        *False* on the connection features list. All others will default
        to True.
    """
    if apps.ready:
        # We're running in a real Django unit test, don't do anything.
        return

    if 'DJANGO_SETTINGS_MODULE' not in os.environ:
        os.environ['DJANGO_SETTINGS_MODULE'] = settings_module
    django.setup()
    mock_django_connection(disabled_features) 
Example 6
Project: scout_apm_python   Author: scoutapp   File: test_django.py    License: MIT License 6 votes vote down vote up
def test_install_middleware_old_style(list_or_tuple, preinstalled):
    if preinstalled:
        middleware = list_or_tuple(
            [
                "scout_apm.django.middleware.OldStyleMiddlewareTimingMiddleware",
                "django.middleware.common.CommonMiddleware",
                "scout_apm.django.middleware.OldStyleViewMiddleware",
            ]
        )
    else:
        middleware = list_or_tuple(["django.middleware.common.CommonMiddleware"])

    with override_settings(MIDDLEWARE_CLASSES=middleware):
        apps.get_app_config("scout_apm").install_middleware()

        assert settings.MIDDLEWARE_CLASSES == list_or_tuple(
            [
                "scout_apm.django.middleware.OldStyleMiddlewareTimingMiddleware",
                "django.middleware.common.CommonMiddleware",
                "scout_apm.django.middleware.OldStyleViewMiddleware",
            ]
        ) 
Example 7
Project: scout_apm_python   Author: scoutapp   File: test_django.py    License: MIT License 6 votes vote down vote up
def test_install_middleware_new_style(list_or_tuple, preinstalled):
    if preinstalled:
        middleware = list_or_tuple(
            [
                "scout_apm.django.middleware.MiddlewareTimingMiddleware",
                "django.middleware.common.CommonMiddleware",
                "scout_apm.django.middleware.ViewTimingMiddleware",
            ]
        )
    else:
        middleware = list_or_tuple(["django.middleware.common.CommonMiddleware"])

    with override_settings(MIDDLEWARE=middleware):
        apps.get_app_config("scout_apm").install_middleware()

        assert settings.MIDDLEWARE == list_or_tuple(
            [
                "scout_apm.django.middleware.MiddlewareTimingMiddleware",
                "django.middleware.common.CommonMiddleware",
                "scout_apm.django.middleware.ViewTimingMiddleware",
            ]
        ) 
Example 8
Project: django-sqlserver   Author: denisenkom   File: runtests.py    License: MIT License 6 votes vote down vote up
def get_test_modules():
    modules = []
    discovery_paths = [(None, RUNTESTS_DIR)]
    if connection.features.gis_enabled:
        # GIS tests are in nested apps
        discovery_paths.append(('gis_tests', os.path.join(RUNTESTS_DIR, 'gis_tests')))
    else:
        SUBDIRS_TO_SKIP.append('gis_tests')

    for modpath, dirpath in discovery_paths:
        for f in os.listdir(dirpath):
            if ('.' in f or
                    os.path.basename(f) in SUBDIRS_TO_SKIP or
                    os.path.isfile(f) or
                    not os.path.exists(os.path.join(dirpath, f, '__init__.py'))):
                continue
            modules.append((modpath, f))
    return modules 
Example 9
Project: djongo   Author: nesdis   File: setup_tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get_test_modules():
    modules = []
    discovery_paths = [(None, RUNTESTS_DIR)]
    if connection.features.gis_enabled:
        # GIS tests are in nested apps
        discovery_paths.append(('gis_tests', os.path.join(RUNTESTS_DIR, 'gis_tests')))
    else:
        SUBDIRS_TO_SKIP.append('gis_tests')

    for modpath, dirpath in discovery_paths:
        for f in os.scandir(dirpath):
            if ('.' not in f.name and
                    os.path.basename(f.name) not in SUBDIRS_TO_SKIP and
                    not f.is_file() and
                    os.path.exists(os.path.join(f.path, '__init__.py'))):
                modules.append((modpath, f.name))
    return modules 
Example 10
Project: djongo   Author: nesdis   File: runtests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get_test_modules():
    modules = []
    discovery_paths = [(None, RUNTESTS_DIR)]
    if connection.features.gis_enabled:
        # GIS tests are in nested apps
        discovery_paths.append(('gis_tests', os.path.join(RUNTESTS_DIR, 'gis_tests')))
    else:
        SUBDIRS_TO_SKIP.append('gis_tests')

    for modpath, dirpath in discovery_paths:
        for f in os.listdir(dirpath):
            if ('.' not in f and
                    os.path.basename(f) not in SUBDIRS_TO_SKIP and
                    not os.path.isfile(f) and
                    os.path.exists(os.path.join(dirpath, f, '__init__.py'))):
                modules.append((modpath, f))
    return modules 
Example 11
Project: djongo   Author: nesdis   File: runtests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get_test_modules():
    modules = []
    discovery_paths = [(None, RUNTESTS_DIR)]
    if connection.features.gis_enabled:
        # GIS tests are in nested apps
        discovery_paths.append(('gis_tests', os.path.join(RUNTESTS_DIR, 'gis_tests')))
    else:
        SUBDIRS_TO_SKIP.append('gis_tests')

    for modpath, dirpath in discovery_paths:
        for f in os.scandir(dirpath):
            if ('.' not in f.name and
                    os.path.basename(f.name) not in SUBDIRS_TO_SKIP and
                    not f.is_file() and
                    os.path.exists(os.path.join(f.path, '__init__.py'))):
                modules.append((modpath, f.name))
    return modules 
Example 12
Project: caluma   Author: projectcaluma   File: test_migration.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_migrate_to_form_question_natural_key_reverse(transactional_db):
    executor = MigrationExecutor(connection)
    app = "caluma_form"
    migrate_from = [(app, "0024_auto_20190919_1244")]
    migrate_to = [(app, "0023_auto_20190729_1448")]

    executor.migrate(migrate_from)
    old_apps = executor.loader.project_state(migrate_from).apps

    # Create some old data. Can't use factories here

    Form = old_apps.get_model(app, "Form")
    Question = old_apps.get_model(app, "Question")
    FormQuestion = old_apps.get_model(app, "FormQuestion")

    form_1 = Form.objects.create(slug="form-1")

    question_1 = Question.objects.create(type="text", slug="question-1")
    FormQuestion.objects.create(form=form_1, question=question_1)

    # Migrate backwards.
    executor.loader.build_graph()  # reload.
    with pytest.raises(DataError):
        executor.migrate(migrate_to) 
Example 13
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_commands():
    """
    Returns a dictionary mapping command names to their callback applications.

    This works by looking for a management.commands package in django.core, and
    in each installed application -- if a commands package exists, all commands
    in that package are registered.

    Core commands are always included. If a settings module has been
    specified, user-defined commands will also be included.

    The dictionary is in the format {command_name: app_name}. Key-value
    pairs from this dictionary can then be used in calls to
    load_command_class(app_name, command_name)

    If a specific version of a command must be loaded (e.g., with the
    startapp command), the instantiated module can be placed in the
    dictionary in place of the application name.

    The dictionary is cached on the first call and reused on subsequent
    calls.
    """
    commands = {name: 'django.core' for name in find_commands(upath(__path__[0]))}

    if not settings.configured:
        return commands

    for app_config in reversed(list(apps.get_app_configs())):
        path = os.path.join(app_config.path, 'management')
        commands.update({name: app_config.name for name in find_commands(path)})

    return commands 
Example 14
Project: GTDWeb   Author: lanbing510   File: base.py    License: GNU General Public License v2.0 5 votes vote down vote up
def handle(self, *app_labels, **options):
        from django.apps import apps
        try:
            app_configs = [apps.get_app_config(app_label) for app_label in app_labels]
        except (LookupError, ImportError) as e:
            raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)
        output = []
        for app_config in app_configs:
            app_output = self.handle_app_config(app_config, **options)
            if app_output:
                output.append(app_output)
        return '\n'.join(output) 
Example 15
Project: django-osm-field   Author: MarkusH   File: test_fields.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        # Taken from IsolatedModelsTestCase in
        # django/tests/invalid_models_tests/base.py
        from django.apps import apps

        self._old_models = apps.app_configs["tests"].models.copy() 
Example 16
Project: django-osm-field   Author: MarkusH   File: test_fields.py    License: MIT License 5 votes vote down vote up
def tearDown(self):
        # Taken from IsolatedModelsTestCase in
        # django/tests/invalid_models_tests/base.py
        from django.apps import apps

        apps.app_configs["tests"].models = self._old_models
        apps.all_models["tests"] = self._old_models
        apps.clear_cache() 
Example 17
Project: DCRM   Author: 82Flex   File: compat.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def is_installed(appname):
        return appname in settings.INSTALLED_APPS #or apps.is_installed(appname) 
Example 18
Project: DCRM   Author: 82Flex   File: compat.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get_django_model(app_label, model_name):
        return apps.get_model(app_label, model_name) 
Example 19
Project: DeerU   Author: gojuukaze   File: __init__.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_commands():
    """
    Return a dictionary mapping command names to their callback applications.

    Look for a management.commands package in django.core, and in each
    installed application -- if a commands package exists, register all
    commands in that package.

    Core commands are always included. If a settings module has been
    specified, also include user-defined commands.

    The dictionary is in the format {command_name: app_name}. Key-value
    pairs from this dictionary can then be used in calls to
    load_command_class(app_name, command_name)

    If a specific version of a command must be loaded (e.g., with the
    startapp command), the instantiated module can be placed in the
    dictionary in place of the application name.

    The dictionary is cached on the first call and reused on subsequent
    calls.
    """
    commands = {name: 'django.core' for name in find_commands(__path__[0])}

    if not settings.configured:
        return commands

    for app_config in reversed(list(apps.get_app_configs())):
        path = os.path.join(app_config.path, 'management')
        commands.update({name: app_config.name for name in find_commands(path)})

    return commands 
Example 20
Project: DeerU   Author: gojuukaze   File: __init__.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_commands():
    """
    Return a dictionary mapping command names to their callback applications.

    Look for a management.commands package in django.core, and in each
    installed application -- if a commands package exists, register all
    commands in that package.

    Core commands are always included. If a settings module has been
    specified, also include user-defined commands.

    The dictionary is in the format {command_name: app_name}. Key-value
    pairs from this dictionary can then be used in calls to
    load_command_class(app_name, command_name)

    If a specific version of a command must be loaded (e.g., with the
    startapp command), the instantiated module can be placed in the
    dictionary in place of the application name.

    The dictionary is cached on the first call and reused on subsequent
    calls.
    """
    commands = {name: 'django.core' for name in find_commands(__path__[0])}

    if not settings.configured:
        return commands

    for app_config in reversed(list(apps.get_app_configs())):
        path = os.path.join(app_config.path, 'management')
        commands.update({name: app_config.name for name in find_commands(path)})

    return commands 
Example 21
Project: sphinxcontrib-django   Author: edoburu   File: docstrings.py    License: Apache License 2.0 5 votes vote down vote up
def _resolve_model(field, to):
    if "." in to:
        return apps.get_model(to)
    elif to == "self":
        return field.model
    else:
        return apps.get_model(field.model._meta.app_label, to) 
Example 22
Project: django-seo   Author: whyflyru   File: tests.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tearDown(self):
        del apps.all_models['djangoseo']['dog'] 
Example 23
Project: django-seo   Author: whyflyru   File: tests.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tearDown(self):
        del apps.all_models['djangoseo']['animal'] 
Example 24
Project: xos   Author: open-cloud   File: grpc_server.py    License: Apache License 2.0 5 votes vote down vote up
def init_django(self):
        try:
            import django

            os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
            django.setup()
            from django.apps import apps

            self.django_apps = apps
            self.django_initialized = True
        except BaseException:
            log.exception("Failed to initialize django") 
Example 25
Project: django-cassandra-engine   Author: r4fek   File: tests.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def setUp(self):
        apps.clear_cache() 
Example 26
Project: django-cassandra-engine   Author: r4fek   File: tests.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_clear_cache_clears_relation_tree(self):
        # The apps.clear_cache is setUp() should have deleted all trees.
        # Exclude abstract models that are not included in the Apps registry
        # and have no cache.
        all_models_with_cache = (m for m in self.all_models if not m._meta.abstract)
        for m in all_models_with_cache:
            self.assertNotIn('_relation_tree', m._meta.__dict__) 
Example 27
Project: django-ra-erp   Author: ra-systems   File: runtests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get_installed():
    ignore_apps = ['crispy_forms']
    return [app_config.name for app_config in apps.get_app_configs() if app_config.name not in ignore_apps] 
Example 28
Project: xos   Author: opencord   File: grpc_server.py    License: Apache License 2.0 5 votes vote down vote up
def init_django(self):
        try:
            import django

            os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings")
            django.setup()
            from django.apps import apps

            self.django_apps = apps
            self.django_initialized = True
        except BaseException:
            log.exception("Failed to initialize django") 
Example 29
Project: rssant   Author: anyant   File: django_setup.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _django_setup():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rssant.settings')
    if not apps.ready and not settings.configured:
        django.setup() 
Example 30
Project: django_coverage_plugin   Author: nedbat   File: plugin.py    License: Apache License 2.0 5 votes vote down vote up
def check_debug():
    """Check that Django's template debugging is enabled.

    Django's built-in "template debugging" records information the plugin needs
    to do its work.  Check that the setting is correct, and raise an exception
    if it is not.

    Returns True if the debug check was performed, False otherwise
    """
    from django.conf import settings

    if not settings.configured:
        return False

    # I _think_ this check is all that's needed and the 3 "hasattr" checks
    # below can be removed, but it's not clear how to verify that
    from django.apps import apps
    if not apps.ready:
        return False

    # django.template.backends.django gets loaded lazily, so return false
    # until they've been loaded
    if not hasattr(django.template, "backends"):
        return False
    if not hasattr(django.template.backends, "django"):
        return False
    if not hasattr(django.template.backends.django, "DjangoTemplates"):
        raise DjangoTemplatePluginException("Can't use non-Django templates.")

    for engine in django.template.engines.all():
        if not isinstance(engine, django.template.backends.django.DjangoTemplates):
            raise DjangoTemplatePluginException(
                "Can't use non-Django templates."
            )
        if not engine.engine.debug:
            raise DjangoTemplatePluginException(
                "Template debugging must be enabled in settings."
            )

    return True