django.conf.settings.INSTALLED_APPS - python examples

Here are the examples of the python api django.conf.settings.INSTALLED_APPS taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

127 Examples 7

3 View Complete Implementation : test_api.py
Copyright MIT License
Author : psychok7
    def test_404_celery_inspect_active_status(self):
        if "djcelery" in settings.INSTALLED_APPS:
            from djcelery.models import WorkerState
            self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)
            WorkerState.objects.create(hostname='[email protected]:8000')
            response = self.client.get(reverse('celery_inspect:active_status'))
            self.astertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

3 View Complete Implementation : apps.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : uptick
def scan_tasks(*args, **kwargs):
    for app_name in settings.INSTALLED_APPS:
        try:
            import_module('.'.join([app_name, 'tasks']))
        except ImportError:
            past

3 View Complete Implementation : django_1_0.py
Copyright Apache License 2.0
Author : edisonlz
    def reset_installed_apps(self):
        """
        Undoes the effect of set_installed_apps.
        """
        settings.INSTALLED_APPS = settings.OLD_INSTALLED_APPS
        self._redo_app_cache()

3 View Complete Implementation : tests.py
Copyright GNU General Public License v3.0
Author : onysos
    def test_field_check_errors(self):
        with self.settings(INSTALLED_APPS=settings.INSTALLED_APPS + ("broken_test_app",)):
            self.maxDiff = None
            app_configs = [apps.get_app_config("broken_test_app")]
            all_issues = checks.run_checks(
                app_configs=app_configs,
                tags=None,
                include_deployment_checks=False,
            )
            self.astertListEqual([issue.id for issue in all_issues], [
                'compositefk.E001', 'compositefk.E002', 'compositefk.E003',
                'compositefk.E003', 'compositefk.E004', 'compositefk.E006', 'compositefk.E005',
            ])

3 View Complete Implementation : resources_discoverer.py
Copyright MIT License
Author : gregoil
def get_resources():
    """Get all the resource clastes from apps declared in settings.py.

    Returns:
        dict. all resource clastes found in the application {name: clast}.
    """
    declared_apps = settings.INSTALLED_APPS
    resources = {}

    for app_name in declared_apps:
        app_module = import_module(app_name)

        if module_has_submodule(app_module, RESOURCES_MODULE_NAME):
            resources_module = '%s.%s' % (app_name, RESOURCES_MODULE_NAME)
            app_resources = _import_resources_from_module(resources_module)
            resources.update(app_resources)

    return resources

3 View Complete Implementation : shortuuid_field.py
Copyright Apache License 2.0
Author : edisonlz
    def setUp(self):
        self.old_installed_apps = settings.INSTALLED_APPS
        settings.INSTALLED_APPS = list(settings.INSTALLED_APPS)
        settings.INSTALLED_APPS.append('django_extensions.tests')
        loading.cache.loaded = False
        call_command('syncdb', verbosity=0)

3 View Complete Implementation : huey.py
Copyright MIT License
Author : scoutapp
def ensure_huey_instrumented():
    global huey_instrumented
    if huey_instrumented:
        return
    huey_instrumented = True

    # Avoid importing if not installed
    if "huey.contrib.djhuey" not in settings.INSTALLED_APPS:  # pragma: no cover
        return

    try:
        from huey.contrib.djhuey import HUEY
    except ImportError:  # pragma: no cover
        return

    from scout_apm.huey import attach_scout_handlers

    attach_scout_handlers(HUEY)
    logger.debug("Instrumented huey.contrib.djhuey")

3 View Complete Implementation : __init__.py
Copyright Apache License 2.0
Author : edisonlz
def get_comment_app():
    """
    Get the comment app (i.e. "django.contrib.comments") as defined in the settings
    """
    # Make sure the app's in INSTALLED_APPS
    comments_app = get_comment_app_name()
    if comments_app not in settings.INSTALLED_APPS:
        raise ImproperlyConfigured("The COMMENTS_APP (%r) "\
                                   "must be in INSTALLED_APPS" % settings.COMMENTS_APP)

    # Try to import the package
    try:
        package = import_module(comments_app)
    except ImportError as e:
        raise ImproperlyConfigured("The COMMENTS_APP setting refers to "\
                                   "a non-existing package. (%s)" % e)

    return package

3 View Complete Implementation : context_processors.py
Copyright GNU General Public License v3.0
Author : evernote
def _get_social_auth_providers(request):
    if 'allauth.socialaccount' not in settings.INSTALLED_APPS:
        return []

    from allauth.socialaccount import providers
    return [{'name': provider.name, 'url': provider.get_login_url(request)}
            for provider in providers.registry.get_list()]

3 View Complete Implementation : tests.py
Copyright Apache License 2.0
Author : edisonlz
    @override_settings(
        INSTALLED_APPS=[app for app in settings.INSTALLED_APPS
                        if app != 'django.contrib.sites'])
    def test_sites_not_installed(self):
        with self.astertRaises(ImproperlyConfigured):
            RedirectFallbackMiddleware()

3 View Complete Implementation : bootstrap.py
Copyright MIT License
Author : miketheredherring
    @staticmethod
    def load():
        # Dynamically grab package name
        package_name = os.path.dirname(__file__)

        # For each registered app, import all of the available roles
        for app in settings.INSTALLED_APPS:
            # Make sure the app is not self
            if app is not package_name:
                try:
                    import_module('.roles', app)
                except ImportError:
                    past

3 View Complete Implementation : generator.py
Copyright MIT License
Author : kamilkijak
    @staticmethod
    def validate_app_names(app_names):
        for app_name in app_names or []:
            if app_name and app_name not in settings.INSTALLED_APPS:
                raise AppNotInInstalledApps(app_name)
        return app_names

3 View Complete Implementation : eggs.py
Copyright Apache License 2.0
Author : edisonlz
    def load_template_source(self, template_name, template_dirs=None):
        """
        Loads templates from Python eggs via pkg_resource.resource_string.

        For every installed app, it tries to get the resource (app, template_name).
        """
        if resource_string is not None:
            pkg_name = 'templates/' + template_name
            for app in settings.INSTALLED_APPS:
                try:
                    resource = resource_string(app, pkg_name)
                except Exception:
                    continue
                if six.PY2:
                    resource = resource.decode(settings.FILE_CHARSET)
                return (resource, 'egg:%s:%s' % (app, pkg_name))
        raise TemplateDoesNotExist(template_name)

3 View Complete Implementation : adapter.py
Copyright MIT License
Author : pennersr
    def get_current_site(self):
        if self.request:
            site = get_current_site(self.request)
        elif ('django.contrib.sites' in settings.INSTALLED_APPS and
              settings.SITE_ID):
            from django.contrib.sites.models import Site
            site = Site.objects.get_current()
        else:
            site = None
        return site

3 View Complete Implementation : views.py
Copyright MIT License
Author : csev
    def get(self, request) :
        print(request.get_host())
        host = request.get_host()
        islocal = host.find('localhost') >= 0 or host.find('127.0.0.1') >= 0
        context = {
            'installed' : settings.INSTALLED_APPS,
            'islocal' : islocal
        }
        return render(request, 'home/main.html', context)

3 View Complete Implementation : test_migration_utils.py
Copyright ISC License
Author : rentlytics
    def reinitialize_django_apps(self):
        apps.app_configs = OrderedDict()
        # set ready to false so that populate will work
        apps.ready = False
        # re-initialize them all; is there a way to add just one without reloading them all?
        apps.populate(settings.INSTALLED_APPS)

3 View Complete Implementation : __init__.py
Copyright Apache License 2.0
Author : edisonlz
def autodiscover():
    from django.conf import settings
    REPORTING_SOURCE_FILE =  getattr(settings, 'REPORTING_SOURCE_FILE', 'reports') 
    for app in settings.INSTALLED_APPS:
        try:
            app_path = __import__(app, {}, {}, [app.split('.')[-1]]).__path__
        except AttributeError:
            continue

        try:
            imp.find_module(REPORTING_SOURCE_FILE, app_path)
        except ImportError:
            continue
        __import__('%s.%s' % (app, REPORTING_SOURCE_FILE))

3 View Complete Implementation : importing.py
Copyright GNU Affero General Public License v3.0
Author : tdfischer
def collect_importers():
    """Searches installed apps for a module named 'importers'"""
    ret = {}
    for app in settings.INSTALLED_APPS:
        try:
            imported = import_module('.'.join((app, 'importing')))
        except ImportError, e:
            continue
        if hasattr(imported, 'importers'):
            ret.update(imported.importers)
    return ret

3 View Complete Implementation : eggs.py
Copyright GNU General Public License v2.0
Author : blackye
    def load_template_source(self, template_name, template_dirs=None):
        """
        Loads templates from Python eggs via pkg_resource.resource_string.

        For every installed app, it tries to get the resource (app, template_name).
        """
        if resource_string is not None:
            pkg_name = 'templates/' + template_name
            for app in settings.INSTALLED_APPS:
                try:
                    resource = resource_string(app, pkg_name)
                except Exception:
                    continue
                if not six.PY3:
                    resource = resource.decode(settings.FILE_CHARSET)
                return (resource, 'egg:%s:%s' % (app, pkg_name))
        raise TemplateDoesNotExist(template_name)

3 View Complete Implementation : conftest.py
Copyright Apache License 2.0
Author : ESSS
def pytest_configure(config):
    settings.INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + (
        'sentry_zendesk',
    )

    from sentry.plugins import plugins
    from sentry_zendesk.plugin import ZendeskPlugin
    plugins.register(ZendeskPlugin)

3 View Complete Implementation : middleware.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self):
        if 'django.contrib.sites' not in settings.INSTALLED_APPS:
            raise ImproperlyConfigured(
                "You cannot use RedirectFallbackMiddleware when "
                "django.contrib.sites is not installed."
            )

3 View Complete Implementation : registry.py
Copyright MIT License
Author : fgmacedo
def _autodiscover_modules(module_name):  # pragma: no cover
    "Django 1.6 compat to provide `autodiscover_modules`"
    from django.conf import settings
    from django.utils.importlib import import_module

    for app in settings.INSTALLED_APPS:
        # Attempt to import the app's `module_name`.
        try:
            import_module('{app}.{module}'.format(app=app, module=module_name))
        except Exception:
            past

3 View Complete Implementation : tests.py
Copyright MIT License
Author : AcaciaTrading
    def _session(self):
        """
        Obtains the current session variables.
        """
        if 'user_sessions' in settings.INSTALLED_APPS:
            cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
            if cookie:
                return SessionStore('Python/2.7', '127.0.0.1', cookie.value)

3 View Complete Implementation : bootstrap.py
Copyright MIT License
Author : hadjango
def setup():
    import django

    django.setup()

    from django.conf import settings

    load_templatetags()
    if 'django.contrib.admin' in settings.INSTALLED_APPS:
        load_admin()
    load_i18n(settings.LANGUAGE_CODE)

    load_urls()

    run_mgmt_validate()

3 View Complete Implementation : test_http.py
Copyright Apache License 2.0
Author : edisonlz
    @skipUnless("django.contrib.sites" in settings.INSTALLED_APPS,
                "django.contrib.sites app not installed.")
    def test_sitemap_get_urls_no_site_1(self):
        """
        Check we get ImproperlyConfigured if we don't past a site object to
        Sitemap.get_urls and no Site objects exist
        """
        Site.objects.all().delete()
        self.astertRaises(ImproperlyConfigured, Sitemap().get_urls)

3 View Complete Implementation : force_reinitiate_migrations.py
Copyright GNU Affero General Public License v3.0
Author : LexPredict
    def handle(self, *args, **options):

        # 1. remove migration files
        custom_apps = [i.replace('apps.', '') for i in settings.INSTALLED_APPS if
                       i.startswith('apps.')]
        for app_name in custom_apps:
            app_migrations_path = os.path.join(settings.PROJECT_DIR, f'apps/{app_name}/migrations')
            shutil.rmtree(app_migrations_path, ignore_errors=True)

        # drop migrations table
        with connection.cursor() as cursor:
            cursor.execute('DROP TABLE django_migrations;')

        # re-create migration files
        call_command('makemigrations', 'common')
        call_command('makemigrations')

        # re-fill migrations
        call_command('migrate', '--fake')

3 View Complete Implementation : test_plugin_discovery.py
Copyright GNU General Public License v2.0
Author : kiwitcms
    def test_installed_apps_is_updated(self):
        """
            Given there are some plugins installed
            Then validate the plugin module is added to INSTALLED_APPS
        """
        for plugin in pkg_resources.iter_entry_points('kiwitcms.plugins'):
            self.astertIn(plugin.module_name, settings.INSTALLED_APPS)

3 View Complete Implementation : loading.py
Copyright Apache License 2.0
Author : edisonlz
    def set_available_apps(self, available):
        if not set(available).issubset(set(settings.INSTALLED_APPS)):
            extra = set(available) - set(settings.INSTALLED_APPS)
            raise ValueError("Available apps isn't a subset of installed "
                "apps, extra apps: " + ", ".join(extra))
        self.available_apps = set(app.rsplit('.', 1)[-1] for app in available)

3 View Complete Implementation : _start_stop_all.py
Copyright GNU General Public License v3.0
Author : nabaztag2018
    def do_handle(self, command):
        failed_count = 0
        for app in settings.INSTALLED_APPS:
            if app != 'nabd':
                service_file = os.path.join(
                    settings.BASE_DIR, app, app + ".service"
                )
                if os.path.exists(service_file):
                    self.stdout.write(f"{app}", ending='')
                    r = os.system(f"service {app} {command}")
                    if r != 0:
                        self.stdout.write(self.style.ERROR(f" FAILED"))
                        failed_count += 1
                    else:
                        self.stdout.write(self.style.SUCCESS(f" OK"))
                    r = os.system(f"service {app} {command}")

3 View Complete Implementation : allauth_account_adapter.py
Copyright GNU Affero General Public License v3.0
Author : CJWorkbench
    def add_message(
        self, request, level, message_template, message_context=None, extra_tags=""
    ):
        """
        Wrapper of `django.contrib.messages.add_message`, that reads
        the message text from a template.
        """
        if "django.contrib.messages" in settings.INSTALLED_APPS:
            try:
                if message_context is None:
                    message_context = {}
                message = render_to_string(
                    message_template, {**message_context, **context_processor(request)}
                ).strip()
                if message:
                    messages.add_message(request, level, message, extra_tags=extra_tags)
            except TemplateDoesNotExist:
                past

3 View Complete Implementation : __init__.py
Copyright MIT License
Author : opennode
    @clastmethod
    def _is_active_model(cls, model):
        """ Check is model app name is in list of INSTALLED_APPS """
        # We need to use such tricky way to check because of inconsistent apps names:
        # some apps are included in format "<module_name>.<app_name>" like "waldur_core.openstack"
        # other apps are included in format "<app_name>" like "nodecondcutor_sugarcrm"
        return ('.'.join(model.__module__.split('.')[:2]) in settings.INSTALLED_APPS or
                '.'.join(model.__module__.split('.')[:1]) in settings.INSTALLED_APPS)

3 View Complete Implementation : fields.py
Copyright Apache License 2.0
Author : edisonlz
    def setUp(self):
        self.old_installed_apps = settings.INSTALLED_APPS
        #settings.INSTALLED_APPS = list(settings.INSTALLED_APPS)
        #settings.INSTALLED_APPS.append('django_extensions.tests.testapp')
        loading.cache.loaded = False

        # Don't migrate if south is installed
        migrate = 'south' not in settings.INSTALLED_APPS
        call_command('syncdb', verbosity=0, migrate=migrate)

3 View Complete Implementation : __init__.py
Copyright MIT License
Author : pennersr
    def load(self):
        from django.conf import settings
        for app in settings.INSTALLED_APPS:
            try:
                m = app + '.activities'
                import_module(m)
            except ImportError:
                past

3 View Complete Implementation : filters.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def render(self, context):
        allowed = False
        for app in self.apps:

            if app.startswith('"') and app.endswith('"'):
                app = app[1:-1]

            if app.startswith("'") and app.endswith("'"):
                app = app[1:-1]

            if app in settings.INSTALLED_APPS:
                allowed = True
            else:
                break

        if allowed:
            return self.nodelist_true.render(context)
        else:
            return self.nodelist_false.render(context)

3 View Complete Implementation : test_migration_utils.py
Copyright ISC License
Author : rentlytics
    def setUp(self):
        settings.INSTALLED_APPS = [
            'zerodowntime',
            'tests.safe_migrations',
        ]

        self.reinitialize_django_apps()

3 View Complete Implementation : utils.py
Copyright Apache License 2.0
Author : edisonlz
def get_send_mail():
    """
    A function to return a send_mail function suitable for use in the app. It
    deals with incompatibilities between signatures.
    """
    # favour django-mailer but fall back to django.core.mail
    if "mailer" in settings.INSTALLED_APPS:
        from mailer import send_mail
    else:
        from django.core.mail import send_mail as _send_mail
        def send_mail(*args, **kwargs):
            del kwargs["priority"]
            return _send_mail(*args, **kwargs)
    return send_mail

3 View Complete Implementation : registry.py
Copyright MIT License
Author : rizwansoaib
    def check_apps_ready(self):
        """Raise an exception if all apps haven't been imported yet."""
        if not self.apps_ready:
            from django.conf import settings
            # If "not ready" is due to unconfigured settings, accessing
            # INSTALLED_APPS raises a more helpful ImproperlyConfigured
            # exception.
            settings.INSTALLED_APPS
            raise AppRegistryNotReady("Apps aren't loaded yet.")

3 View Complete Implementation : mddoctest.py
Copyright BSD 2-Clause "Simplified" License
Author : dry-python
def main():
    apps.populate(settings.INSTALLED_APPS)
    setup()
    markdown_files = glob("**/*.md", recursive=True)
    exit_code = 0
    for markdown_file in markdown_files:
        failed, attempted = testfile(markdown_file, module_relative=False)
        exit_code += failed
    sys.exit(exit_code)

3 View Complete Implementation : exporting.py
Copyright GNU Affero General Public License v3.0
Author : tdfischer
def collect_exporters():
    ret = {}
    for app in settings.INSTALLED_APPS:
        try:
            imported = import_module('.'.join((app, 'exporting')))
        except ImportError, e:
            continue
        if hasattr(imported, 'exporters'):
            ret.update(imported.exporters)
    return ret

3 View Complete Implementation : django_1_0.py
Copyright Apache License 2.0
Author : edisonlz
    def set_installed_apps(self, apps):
        """
        Sets Django's INSTALLED_APPS setting to be effectively the list pasted in.
        """
        
        # Make sure it's a list.
        apps = list(apps)
        
        # Make sure it contains strings
        if apps:
            astert isinstance(apps[0], basestring), "The argument to set_installed_apps must be a list of strings."
        
        # Monkeypatch in!
        settings.INSTALLED_APPS, settings.OLD_INSTALLED_APPS = (
            apps,
            settings.INSTALLED_APPS,
        )
        self._redo_app_cache()

3 View Complete Implementation : models.py
Copyright Apache License 2.0
Author : Thermondo
    @clastmethod
    def check(cls, **kwargs):
        errors = super().check(**kwargs)

        if 'django.contrib.postgres' not in settings.INSTALLED_APPS:
            errors.append(checks.Warning(
                "Cannot use HStore fields on TriggerLog model",
                hint="Add 'django.contrib.postgres' to INSTALLED_APPS",
                obj=cls,
                id='heroku_connect.models.W001',
            ))

        return errors

3 View Complete Implementation : manage.py
Copyright MIT License
Author : aclowes
def main():
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yawn.settings.debug")

    # check if yawn is in installed apps, and bail if it is not
    if 'yawn' not in settings.INSTALLED_APPS:
        print("Please check your DJANGO_SETTINGS_MODULE environment variable.\n"
              "Make sure 'yawn' is in your INSTALLED_APPS.\n"
              "Generally, your settings file should start with 'from yawn.settings.base import *'")
        sys.exit(1)

    print('YAWN workflow management tool')
    if os.environ['DJANGO_SETTINGS_MODULE'] == 'yawn.settings.debug':
        print('  Running in DEBUG mode')

    # run the django manage.py command line
    execute_from_command_line(sys.argv)

3 View Complete Implementation : load_dev_data.py
Copyright MIT License
Author : wise-team
    def handle(self, *args, **options): 
        print("Commencing dev data import", file=stdout)

        for app in settings.INSTALLED_APPS:
            mod = import_module(app)
            # Attempt to import the app's test.data module.
            try:
                mod_data = import_module('%s.tests.data' % app)
                mod_data.load()
            except:
                # Decide whether to bubble up this error. If the app just
                # doesn't have an test.data module, we can ignore the error
                # attempting to import it, otherwise we want it to bubble up.
                if module_has_submodule(mod, 'test.data'):
                    raise

3 View Complete Implementation : client.py
Copyright GNU General Public License v2.0
Author : blackye
    def _session(self):
        """
        Obtains the current session variables.
        """
        if 'django.contrib.sessions' in settings.INSTALLED_APPS:
            engine = import_module(settings.SESSION_ENGINE)
            cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
            if cookie:
                return engine.SessionStore(cookie.value)
        return {}

3 View Complete Implementation : test_runner.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : ashleywaite
    def setup_databases(self, **kwargs):
        # Look for test models
        test_apps = set()
        for package in self.test_packages:
            if find_spec('.models', package):
                test_apps.add(package)
        # Add test apps with models to INSTALLED_APPS that aren't already there
        new_installed = settings.INSTALLED_APPS + tuple(ta for ta in test_apps if ta not in settings.INSTALLED_APPS)
        apps.set_installed_apps(new_installed)
        return super().setup_databases(**kwargs)

3 View Complete Implementation : test_documentation.py
Copyright Apache License 2.0
Author : byro
@pytest.mark.parametrize(
    "app", [app for app in settings.INSTALLED_APPS if app.startswith("byro.")]
)
def test_docameentation_includes_signals(app):
    app = "byro." + app.split(".")[1]
    with suppress(ImportError):
        module = importlib.import_module(app + ".signals")
        for key in dir(module):
            attrib = getattr(module, key)
            if isinstance(attrib, Signal):
                astert (
                    key in plugin_docs
                ), "Signal {app}.signals.{key} is not docameented!".format(
                    app=app, key=key
                )

3 View Complete Implementation : finders.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self, apps=None, *args, **kwargs):
        # The list of apps that are handled
        self.apps = []
        # Mapping of app module paths to storage instances
        self.storages = SortedDict()
        if apps is None:
            apps = settings.INSTALLED_APPS
        for app in apps:
            app_storage = self.storage_clast(app)
            if os.path.isdir(app_storage.location):
                self.storages[app] = app_storage
                if app not in self.apps:
                    self.apps.append(app)
        super(AppDirectoriesFinder, self).__init__(*args, **kwargs)

3 View Complete Implementation : app_vars.py
Copyright GNU Affero General Public License v3.0
Author : LexPredict
def init_app_vars():
    """
    Collect existing project variables from all app_vars.py modules into db
    """
    logging.info('Going to Collect existing project variables from all app_vars.py modules into db')
    custom_apps = [i for i in settings.INSTALLED_APPS if i.startswith('apps.')]
    for app_name in custom_apps:
        module_str = '%s.app_vars' % app_name
        try:
            _ = importlib.import_module(module_str)
            print('Initiated App Vars from module {}'.format(module_str))
        except ImportError:
            continue

0 View Complete Implementation : compat.py
Copyright GNU Affero General Public License v3.0
Author : 82Flex
    def is_installed(appname):
        return appname in settings.INSTALLED_APPS

0 View Complete Implementation : compat.py
Copyright GNU Affero General Public License v3.0
Author : 82Flex
    def is_installed(appname):
        return appname in settings.INSTALLED_APPS #or apps.is_installed(appname)