Python django.conf.settings.INSTALLED_APPS Examples

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

Example 1
Project: django-badgify   Author: ulule   File: registry.py    License: MIT License 6 votes vote down vote up
def _autodiscover(recipes):
    import copy
    from django.conf import settings

    try:
        # py27 / py3 only
        from importlib import import_module
    except ImportError:
        from django.utils.importlib import import_module

    from django.utils.module_loading import module_has_submodule

    for app in settings.INSTALLED_APPS:
        mod = import_module(app)
        try:
            before_import_recipes = copy.copy(recipes)
            import_module('%s.badgify_recipes' % app)
        except Exception:
            recipes = before_import_recipes
            if module_has_submodule(mod, 'badgify_recipes'):
                raise 
Example 2
Project: kobo-predict   Author: awemulya   File: filters.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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) 
Example 3
Project: django-celery-inspect   Author: psychok7   File: viewsets.py    License: MIT License 6 votes vote down vote up
def active_status(self, request):
        """
        This will only work if you have django-celery installed (for now).
        In case you only need to work with status codes to find out if the
        workers are up or not.
        This will only work if we assume our db only contains "active workers".
        To use this feature, you must ensure you use only named workers,
        For example: "-n worker1@localhost:8000".
        http://docs.celeryproject.org/en/latest/userguide/workers.html#starting-the-worker
        """

        app_installed = "djcelery" in settings.INSTALLED_APPS
        if not app_installed:
            return Response(status=status.HTTP_501_NOT_IMPLEMENTED)

        from djcelery.models import WorkerState

        count_workers = WorkerState.objects.all().count()
        result = self.inspect.active()

        if result is not None and count_workers == len(result):
            return Response(status=status.HTTP_200_OK)

        return Response(status=status.HTTP_404_NOT_FOUND) 
Example 4
Project: DCRM   Author: 82Flex   File: template.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get_app_template_dir(app_name):
    """Get the template directory for an application

    We do not use django.db.models.get_app, because this will fail if an
    app does not have any models.

    Returns a full path, or None if the app was not found.
    """
    from django.conf import settings
    from importlib import import_module
    if app_name in _cache:
        return _cache[app_name]
    template_dir = None
    for app in settings.INSTALLED_APPS:
        if app.split('.')[-1] == app_name:
            # Do not hide import errors; these should never happen at this point
            # anyway
            mod = import_module(app)
            template_dir = join(abspath(dirname(mod.__file__)), 'templates')
            break
    _cache[app_name] = template_dir
    return template_dir 
Example 5
Project: bioforum   Author: reBiocoder   File: __init__.py    License: MIT License 6 votes vote down vote up
def setup(set_prefix=True):
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    Set the thread-local urlresolvers script prefix if `set_prefix` is True.
    """
    from django.apps import apps
    from django.conf import settings
    from django.urls import set_script_prefix
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    if set_prefix:
        set_script_prefix(
            '/' if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME
        )
    apps.populate(settings.INSTALLED_APPS) 
Example 6
Project: django-tenants   Author: django-tenants   File: __init__.py    License: MIT License 6 votes vote down vote up
def handle(self, *args, **options):
        self.sync_tenant = options.get('tenant')
        self.sync_public = options.get('shared')
        self.schema_name = options.get('schema_name')
        self.executor = options.get('executor')
        self.installed_apps = settings.INSTALLED_APPS
        self.args = args
        self.options = options

        if self.schema_name:
            if self.sync_public:
                raise CommandError("schema should only be used with the --tenant switch.")
            elif self.schema_name == get_public_schema_name():
                self.sync_public = True
            else:
                self.sync_tenant = True
        elif not self.sync_public and not self.sync_tenant:
            # no options set, sync both
            self.sync_tenant = True
            self.sync_public = True

        if hasattr(settings, 'TENANT_APPS'):
            self.tenant_apps = settings.TENANT_APPS
        if hasattr(settings, 'SHARED_APPS'):
            self.shared_apps = settings.SHARED_APPS 
Example 7
Project: django-tabbed-admin   Author: omji   File: tests.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_medias_method_with_grappelli(self):
        """
        Tests if the right css ile is triggered when grappelli is installed.
        """
        try:
            import grappelli
        except ImportError:
            return
        settings.INSTALLED_APPS += ('grappelli', )
        self.assertIn('grappelli', settings.INSTALLED_APPS)
        admin = BandAdmin(Band, self.site)
        medias = admin.media
        self.assertTrue(len(medias._css) > 0)
        self.assertIn('all', medias._css)
        self.assertTrue(len(medias._css['all']) == 1)
        self.assertIn('grappelli', medias._css['all'][0]) 
Example 8
Project: django-ra-erp   Author: ra-systems   File: checks.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def check_crequest(app_configs=None, **kwargs):
    errors = []
    if 'crequest' not in settings.INSTALLED_APPS:
        errors.append(
            Error('crequest app is missing',
                  hint='Add `crequest` to INSTALLED_APPS',
                  obj='settings',
                  id='ra.E003',
                  )
        )
    if 'crequest.middleware.CrequestMiddleware' not in settings.MIDDLEWARE:
        errors.append(
            Error('crequest middleware is missing',
                  hint='Add "crequest.middleware.CrequestMiddleware" to MIDDLEWARE',
                  obj='settings',
                  id='ra.E003',
                  )
        )
    return errors 
Example 9
Project: yawn   Author: aclowes   File: manage.py    License: MIT License 6 votes vote down vote up
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) 
Example 10
Project: django-suit-dashboard   Author: pawamoy   File: views.py    License: ISC License 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        """
        Django view get function.

        Add items of extra_context, crumbs and grid to context.

        Args:
            request (): Django's request object.
            *args (): request args.
            **kwargs (): request kwargs.

        Returns:
            response: render to response with context.
        """
        context = self.get_context_data(**kwargs)
        context.update(self.extra_context)
        context['crumbs'] = self.get_crumbs()
        context['title'] = self.title
        context['suit'] = 'suit' in settings.INSTALLED_APPS
        if context.get('dashboard_grid', None) is None and self.grid:
            context['dashboard_grid'] = self.grid
        return self.render_to_response(context) 
Example 11
Project: lexpredict-contraxsuite   Author: LexPredict   File: plugins.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def collect_plugins_in_apps(module_name: str, module_attr: str) -> Dict[str, Any]:
    """
    Searches for [module_name].py in each app. If there is such module and it has
    [module_attr] attribute in it then add it to the resulting dictionary with key = application name.

    This way we can provide a pluggable architecture for various subsystems.
    For example:
        Documents app searches for "python_coded_fields.py" in each available app.
        It takes PYTHON_CODED_FIELDS list from each found module and puts fields from it in the
        big field registry.
    """
    res = dict()
    custom_apps = [i for i in settings.INSTALLED_APPS if i.startswith('apps.')]
    for app_name in custom_apps:
        module_str = '{0}.{1}'.format(app_name, module_name)
        try:
            app_module = importlib.import_module(module_str)
            if hasattr(app_module, module_attr):
                plugin = getattr(app_module, module_attr)
                res[app_name] = plugin
        except ImportError:
            continue

    return res 
Example 12
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') 
Example 13
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: __init__.py    License: MIT License 6 votes vote down vote up
def setup(set_prefix=True):
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    Set the thread-local urlresolvers script prefix if `set_prefix` is True.
    """
    from django.apps import apps
    from django.conf import settings
    from django.urls import set_script_prefix
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    if set_prefix:
        set_script_prefix(
            '/' if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME
        )
    apps.populate(settings.INSTALLED_APPS) 
Example 14
Project: zentral   Author: zentralopensource   File: base_extras.py    License: Apache License 2.0 6 votes vote down vote up
def setup_dropdown(context):
    if not SETUP_DROPDOWN:
        for app_name in settings.INSTALLED_APPS:
            app_shortname = app_name.rsplit('.', 1)[-1]
            try:
                url_module = import_module('{}.urls'.format(app_name))
            except ImportError:
                # TODO: ModuleNotFoundError for python >= 3.6
                continue
            setup_menu_cfg = getattr(url_module, 'setup_menu_cfg', None)
            if not setup_menu_cfg:
                logger.info('App %s w/o setup menu config', app_name)
                continue
            section_cfg = {'app_shortname': app_shortname,
                           'title': setup_menu_cfg.get('title', None) or app_shortname.title(),
                           'link_list': [],
                           'weight': setup_menu_cfg.get('weight', 1000)}
            for url_name, anchor_text in setup_menu_cfg['items']:
                section_cfg['link_list'].append((reverse('{}:{}'.format(app_shortname, url_name)),
                                                 anchor_text))
            SETUP_DROPDOWN.append(section_cfg)
        SETUP_DROPDOWN.sort(key=lambda d: (d['weight'], d['title']))
    context["active"] = context.get("setup", False)
    context["section_list"] = SETUP_DROPDOWN
    return context 
Example 15
Project: django-apptemplates   Author: bittner   File: __init__.py    License: MIT License 6 votes vote down vote up
def get_app_template_dir(app_name):
    """
    Get the template directory for an application

    We do not use django.db.models.get_app, because this will fail if an
    app does not have any models.

    Returns a full path, or None if the app was not found.
    """
    if app_name in _cache:
        return _cache[app_name]
    template_dir = None
    for app in settings.INSTALLED_APPS:
        if app.split('.')[-1] == app_name:
            # Do not hide import errors; these should never happen at this
            # point anyway
            mod = import_module(app)
            template_dir = join(abspath(dirname(mod.__file__)), 'templates')
            break
    _cache[app_name] = template_dir
    return template_dir 
Example 16
Project: python   Author: Yeah-Kun   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def setup(set_prefix=True):
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    Set the thread-local urlresolvers script prefix if `set_prefix` is True.
    """
    from django.apps import apps
    from django.conf import settings
    from django.urls import set_script_prefix
    from django.utils.encoding import force_text
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    if set_prefix:
        set_script_prefix(
            '/' if settings.FORCE_SCRIPT_NAME is None else force_text(settings.FORCE_SCRIPT_NAME)
        )
    apps.populate(settings.INSTALLED_APPS) 
Example 17
Project: django-admin-interface   Author: fabiocaccamo   File: test_settings.py    License: MIT License 6 votes vote down vote up
def __test_installed_apps(self):
        dj_version = django.VERSION
        installed_apps = settings.INSTALLED_APPS

        if 'colorfield' not in installed_apps:
            self.assertRaises(ImproperlyConfigured, check_installed_apps)

        elif 'flat' not in installed_apps and dj_version < (1, 9):
            self.assertRaises(ImproperlyConfigured, check_installed_apps)

        elif 'flat' in installed_apps and dj_version >= (1, 9):
            self.assertRaises(ImproperlyConfigured, check_installed_apps)

        elif 'flat_responsive' not in installed_apps and dj_version < (2, 0):
            self.assertRaises(ImproperlyConfigured, check_installed_apps)

        elif 'flat_responsive' in installed_apps and dj_version >= (2, 0):
            self.assertRaises(ImproperlyConfigured, check_installed_apps)

        else:
            check_installed_apps() 
Example 18
Project: luscan-devel   Author: blackye   File: loading.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_app(self, app_label, emptyOK=False):
        """
        Returns the module containing the models for the given app_label. If
        the app has no models in it and 'emptyOK' is True, returns None.
        """
        self._populate()
        imp.acquire_lock()
        try:
            for app_name in settings.INSTALLED_APPS:
                if app_label == app_name.split('.')[-1]:
                    mod = self.load_app(app_name, False)
                    if mod is None:
                        if emptyOK:
                            return None
                        raise ImproperlyConfigured("App with label %s is missing a models.py module." % app_label)
                    else:
                        return mod
            raise ImproperlyConfigured("App with label %s could not be found" % app_label)
        finally:
            imp.release_lock() 
Example 19
Project: django-rest-registration   Author: apragacz   File: checks.py    License: MIT License 5 votes vote down vote up
def _is_auth_token_manager_app_name_installed() -> bool:
    auth_token_manager = _get_auth_token_manager()
    app_names = auth_token_manager.get_app_names()
    return all(app_name in settings.INSTALLED_APPS for app_name in app_names) 
Example 20
Project: coursys   Author: sfu-fas   File: testing.py    License: GNU General Public License v3.0 5 votes vote down vote up
def login_user(self, userid):
        """
        Login as specified user, does not depend on auth backend (hopefully)

        This is based on Client.login() with a small hack that does not
        require the call to authenticate()
        """
        if not 'django.contrib.sessions' in settings.INSTALLED_APPS:
            raise AssertionError("Unable to login without django.contrib.sessions in INSTALLED_APPS")
        try:
            user = User.objects.get(username=userid)
        except User.DoesNotExist:
            user = User(username=userid, password='')
            user.save()
        user.backend = "%s.%s" % ("django.contrib.auth.backends",
                                  "ModelBackend")
        engine = import_module(settings.SESSION_ENGINE)

        # Create a fake request to store login details.
        request = HttpRequest()
        #if self.session:
        #    request.session = self.session
        #else:
        request.session = engine.SessionStore()
        login(request, user)

        # Set the cookie to represent the session.
        session_cookie = settings.SESSION_COOKIE_NAME
        self.cookies[session_cookie] = request.session.session_key
        cookie_data = {
            'max-age': None,
            'path': '/',
            'domain': settings.SESSION_COOKIE_DOMAIN,
            'secure': settings.SESSION_COOKIE_SECURE or None,
            'expires': None,
        }
        self.cookies[session_cookie].update(cookie_data)

        # Save the session values.
        request.session.save() 
Example 21
Project: python-webpack   Author: markfinger   File: apps.py    License: MIT License 5 votes vote down vote up
def ready(self):
        if (
            ('staticfiles' in settings.INSTALLED_APPS or 'django.contrib.staticfiles' in settings.INSTALLED_APPS) and
            FINDER_PATH not in settings.STATICFILES_FINDERS
        ):
            raise ImproperlyConfigured(
                (
                    'When using webpack together with staticfiles, please add \'{}\' to the '
                    'STATICFILES_FINDERS setting.'
                ).format(FINDER_PATH)
            )

        webpack.conf.settings.configure(
            **getattr(settings, 'WEBPACK', {})
        ) 
Example 22
Project: django-dynamic-db-router   Author: ambitioninc   File: run_tests.py    License: MIT License 5 votes vote down vote up
def run_tests(*test_args, **kwargs):
    if 'south' in settings.INSTALLED_APPS:
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()

    if not test_args:
        test_args = ['dynamic_db_router']

    kwargs.setdefault('interactive', False)

    test_runner = NoseTestSuiteRunner(**kwargs)

    failures = test_runner.run_tests(test_args)
    sys.exit(failures) 
Example 23
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def setup():
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    """
    from django.apps import apps
    from django.conf import settings
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    apps.populate(settings.INSTALLED_APPS) 
Example 24
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def setup():
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    """
    from django.apps import apps
    from django.conf import settings
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    apps.populate(settings.INSTALLED_APPS) 
Example 25
Project: GTDWeb   Author: lanbing510   File: base.py    License: GNU General Public License v2.0 5 votes vote down vote up
def model_unpickle(model_id, attrs, factory):
    """
    Used to unpickle Model subclasses with deferred fields.
    """
    if isinstance(model_id, tuple):
        if not apps.ready:
            apps.populate(settings.INSTALLED_APPS)
        model = apps.get_model(*model_id)
    else:
        # Backwards compat - the model was cached directly in earlier versions.
        model = model_id
    cls = factory(model, attrs)
    return cls.__new__(cls) 
Example 26
Project: GTDWeb   Author: lanbing510   File: testcases.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _pre_setup(self):
        """Performs any pre-test setup. This includes:

        * If the class has an 'available_apps' attribute, restricting the app
          registry to these applications, then firing post_migrate -- it must
          run with the correct set of applications for the test case.
        * If the class has a 'fixtures' attribute, installing these fixtures.
        """
        super(TransactionTestCase, self)._pre_setup()
        if self.available_apps is not None:
            apps.set_available_apps(self.available_apps)
            setting_changed.send(sender=settings._wrapped.__class__,
                                 setting='INSTALLED_APPS',
                                 value=self.available_apps,
                                 enter=True)
            for db_name in self._databases_names(include_mirrors=False):
                flush.Command.emit_post_migrate(verbosity=0, interactive=False, database=db_name)
        try:
            self._fixture_setup()
        except Exception:
            if self.available_apps is not None:
                apps.unset_available_apps()
                setting_changed.send(sender=settings._wrapped.__class__,
                                     setting='INSTALLED_APPS',
                                     value=settings.INSTALLED_APPS,
                                     enter=False)

            raise 
Example 27
Project: GTDWeb   Author: lanbing510   File: testcases.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _post_teardown(self):
        """Performs any post-test things. This includes:

        * Flushing the contents of the database, to leave a clean slate. If
          the class has an 'available_apps' attribute, post_migrate isn't fired.
        * Force-closing the connection, so the next test gets a clean cursor.
        """
        try:
            self._fixture_teardown()
            super(TransactionTestCase, self)._post_teardown()
            if self._should_reload_connections():
                # Some DB cursors include SQL statements as part of cursor
                # creation. If you have a test that does a rollback, the effect
                # of these statements is lost, which can affect the operation of
                # tests (e.g., losing a timezone setting causing objects to be
                # created with the wrong time). To make sure this doesn't
                # happen, get a clean connection at the start of every test.
                for conn in connections.all():
                    conn.close()
        finally:
            if self.available_apps is not None:
                apps.unset_available_apps()
                setting_changed.send(sender=settings._wrapped.__class__,
                                     setting='INSTALLED_APPS',
                                     value=settings.INSTALLED_APPS,
                                     enter=False) 
Example 28
Project: FIR   Author: certsocietegenerale   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def check_smime_status():
    if 'djembe' in settings.INSTALLED_APPS \
            and settings.EMAIL_BACKEND == 'djembe.backends.EncryptingSMTPBackend':
        return True
    return False 
Example 29
Project: django-celery-inspect   Author: psychok7   File: test_api.py    License: MIT License 5 votes vote down vote up
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='worker1@localhot:8000')
            response = self.client.get(reverse('celery_inspect:active_status'))
            self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) 
Example 30
Project: django-celery-inspect   Author: psychok7   File: test_api.py    License: MIT License 5 votes vote down vote up
def test_501_celery_inspect_active_status(self):
        if "djcelery" not in settings.INSTALLED_APPS:
            self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)
            response = self.client.get(reverse('celery_inspect:active_status'))
            self.assertEqual(response.status_code, status.HTTP_501_NOT_IMPLEMENTED)