Python django.conf.settings.INSTALLED_APPS Examples
The following are 30
code examples of django.conf.settings.INSTALLED_APPS().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.conf.settings
, or try the search function
.
Example #1
Source File: __init__.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
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 #2
Source File: __init__.py From bioforum with MIT License | 6 votes |
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 #3
Source File: template.py From DCRM with GNU Affero General Public License v3.0 | 6 votes |
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 #4
Source File: views.py From django-suit-dashboard with ISC License | 6 votes |
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 #5
Source File: __init__.py From django-tenants with MIT License | 6 votes |
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 #6
Source File: plugins.py From lexpredict-contraxsuite with GNU Affero General Public License v3.0 | 6 votes |
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 #7
Source File: viewsets.py From django-celery-inspect with MIT License | 6 votes |
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 #8
Source File: base_extras.py From zentral with Apache License 2.0 | 6 votes |
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 #9
Source File: __init__.py From django-apptemplates with MIT License | 6 votes |
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 #10
Source File: filters.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
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 #11
Source File: __init__.py From python with Apache License 2.0 | 6 votes |
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 #12
Source File: tests.py From django-tabbed-admin with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #13
Source File: force_reinitiate_migrations.py From lexpredict-contraxsuite with GNU Affero General Public License v3.0 | 6 votes |
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 #14
Source File: manage.py From yawn with MIT License | 6 votes |
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 #15
Source File: test_settings.py From django-admin-interface with MIT License | 6 votes |
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 #16
Source File: registry.py From django-badgify with MIT License | 6 votes |
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 #17
Source File: checks.py From django-ra-erp with GNU Affero General Public License v3.0 | 6 votes |
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 #18
Source File: loading.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
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
Source File: apps.py From openwisp-utils with BSD 3-Clause "New" or "Revised" License | 5 votes |
def api_enabled(self): return 'rest_framework' in settings.INSTALLED_APPS and self.API_ENABLED
Example #20
Source File: app_vars.py From lexpredict-contraxsuite with GNU Affero General Public License v3.0 | 5 votes |
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
Example #21
Source File: simpletags.py From ishare with MIT License | 5 votes |
def has_enable_admindoc(): from django.conf import settings apps = settings.INSTALLED_APPS return 'django.contrib.admindocs' in apps
Example #22
Source File: testcases.py From python with Apache License 2.0 | 5 votes |
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 #23
Source File: tests.py From acacia_main with MIT License | 5 votes |
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)
Example #24
Source File: context_processors.py From zing with GNU General Public License v3.0 | 5 votes |
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() ]
Example #25
Source File: manage.py From django-pyqt with MIT License | 5 votes |
def deploy(): if not os.path.isfile(configFile): print("Missing config.json") hidden_imports = [] else: with open(configFile) as f: config = json.load(f) hidden_imports = config["hidden-imports"] if config["django"] : for app in settings.INSTALLED_APPS: if app.startswith('django.'): hidden_imports.append(app + '.apps') else: hidden_imports.append(app) cmd = "pyinstaller __main__.py " for i in hidden_imports: cmd += " --hidden-import " cmd += i os.system(cmd) if config["django"]: dist_dir = os.path.join(os.path.join(settings.BASE_DIR, 'dist'), '__main__') if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3': if os.path.isfile(settings.DATABASES['default']['NAME']) : if os.path.isdir(dist_dir): shutil.copy(settings.DATABASES['default']['NAME'], dist_dir) else: print("{} was not found".format(settings.DATABASES['default']['NAME']) ) if settings.LANGUAGES is not None: for lang in settings.LANGUAGES: execute_django_command(["makemessages", "-l", lang[0]]) execute_django_command(["compilemessages"]) try: shutil.copytree(settings.LOCALE_PATHS[0], os.path.join(dist_dir, '.locale')) except Exception as e: print(e)
Example #26
Source File: manage.py From django-pyqt with MIT License | 5 votes |
def migrate_apps(apps, cmd=""): apps_to_migrate = ["makemigrations"] if len(apps) == 0: # Migrate all apps for app in os.listdir(appsDir): if os.path.isdir(os.path.join(appsDir, app)): if app == "__pycache__": pass else: apps_to_migrate.append(app) else: for app in apps: if os.path.isdir(os.path.join(appsDir, app)): apps_to_migrate.append(app) else: print("App <{}> does not exist, make sure you typed the name correctly".format(app)) print('') apps_to_prepare = "" for app in settings.INSTALLED_APPS : if app.startswith("apps."): apps_to_prepare += app.split('.')[1] apps_to_prepare += " " if cmd == "makemigrations": print('Preparing {}'.format(apps_to_prepare)) execute_django_command(apps_to_migrate) elif cmd == "migrate": print("Migrating {}".format(apps_to_prepare)) execute_django_command(['migrate'])
Example #27
Source File: manage.py From django-pyqt with MIT License | 5 votes |
def deploy(): hidden_imports = ['http.cookies', 'html.parser', 'settings', 'apps', 'django.template.defaulttags', 'django.templatetags.i18n', 'django.template.loader_tags', 'django.utils.translation' ] for app in settings.INSTALLED_APPS: if app.startswith('django.'): hidden_imports.append(app + '.apps') else: hidden_imports.append(app) cmd = "pyinstaller __main__.py " for i in hidden_imports: cmd += " --hidden-import " cmd += i os.system(cmd) if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3': dist_dir = os.path.join(os.path.join(settings.BASE_DIR, 'dist'), '__main__') if os.path.isdir(dist_dir): shutil.copy(settings.DATABASES['default']['NAME'], dist_dir) if settings.LANGUAGES is not None: for lang in settings.LANGUAGES: execute_django_command(["makemessages", "-l", lang[0]]) execute_django_command(["compilemessages"]) try: shutil.copytree(settings.LOCALE_PATHS[0], os.path.join(dist_dir, '.locale')) except Exception as e: print(e)
Example #28
Source File: manage.py From django-pyqt with MIT License | 5 votes |
def deploy(): hidden_imports = ['http.cookies', 'html.parser', 'settings', 'apps', 'django.template.defaulttags', 'django.templatetags.i18n', 'django.template.loader_tags', 'django.utils.translation' ] for app in settings.INSTALLED_APPS: if app.startswith('django.'): hidden_imports.append(app + '.apps') else: hidden_imports.append(app) cmd = "pyinstaller __main__.py " for i in hidden_imports: cmd += " --hidden-import " cmd += i os.system(cmd) if settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3': dist_dir = os.path.join(os.path.join(settings.BASE_DIR, 'dist'), '__main__') if os.path.isdir(dist_dir): shutil.copy(settings.DATABASES['default']['NAME'], dist_dir) if settings.LANGUAGES is not None: for lang in settings.LANGUAGES: execute_django_command(["makemessages", "-l", lang[0]]) execute_django_command(["compilemessages"]) try: shutil.copytree(settings.LOCALE_PATHS[0], os.path.join(dist_dir, '.locale')) except Exception as e: print(e)
Example #29
Source File: clear_migrations.py From Django-blog with MIT License | 5 votes |
def handle(self, *args, **options): def get_app(): """ 获取settings里的所有app """ for app in settings.INSTALLED_APPS: path = os.path.join(settings.BASE_DIR, app.replace(".", "/"), "migrations") if os.path.exists(path): yield app, path def clear(path): shutil.rmtree(path) # 递归删除目录 os.makedirs(path) with open(os.path.join(path, "__init__.py"), "w+") as ff: # 创建__init__包文件 pass # 执行命令migrate --fake app zero for app_name, app_path in get_app(): # D:\A-python\Django-blog\env\Scripts\python.exe manage.py migrate --fake user zero os.system(f"{sys.executable} manage.py migrate --fake {app_name} zero") # sys.executable 当前python解释器 # 和上面分开写, 先fake全部app后再clear, 防止 Dependency on app with no migrations: [app]错误 for app_name, app_path in get_app(): clear(app_path) self.stdout.write(self.style.SUCCESS(f"\nClear app: {app_name} migrations done\n")) # 进行初始化的迁移 python manage.py migrate --help 查看帮助信息 self.stdout.write(self.style.SUCCESS('\nRunning makemigrations and migrate --fake-initial\n\n')) os.system(f"{sys.executable} manage.py makemigrations") os.system(f"{sys.executable} manage.py migrate --fake-initial") self.stdout.write(self.style.SUCCESS('\nSuccessfully cleared!'))
Example #30
Source File: runtests.py From gro-api with GNU General Public License v2.0 | 5 votes |
def runtests(): settings_module = 'gro_api.gro_api.test_settings' os.environ['DJANGO_SETTINGS_MODULE'] = settings_module load_env() # Our settings file monkey patches django.setup, so we have to force django # to load it before calling django.setup settings.INSTALLED_APPS from django import setup setup() test_runner = get_runner(settings) failures = test_runner(verbosity=1, interactive=True).run_tests(()) sys.exit(failures)