Python django.apps.apps.get_app_config() Examples
The following are 30
code examples of django.apps.apps.get_app_config().
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.apps.apps
, or try the search function
.
Example #1
Source File: test_counts.py From zulip with Apache License 2.0 | 6 votes |
def test_do_drop_single_stat(self) -> None: user = self.create_user() stream = self.create_stream_with_recipient()[0] count_args_to_delete = {'property': 'to_delete', 'end_time': self.TIME_ZERO, 'value': 10} count_args_to_save = {'property': 'to_save', 'end_time': self.TIME_ZERO, 'value': 10} for count_args in [count_args_to_delete, count_args_to_save]: UserCount.objects.create(user=user, realm=user.realm, **count_args) StreamCount.objects.create(stream=stream, realm=stream.realm, **count_args) RealmCount.objects.create(realm=user.realm, **count_args) InstallationCount.objects.create(**count_args) FillState.objects.create(property='to_delete', end_time=self.TIME_ZERO, state=FillState.DONE) FillState.objects.create(property='to_save', end_time=self.TIME_ZERO, state=FillState.DONE) analytics = apps.get_app_config('analytics') for table in list(analytics.models.values()): self.assertTrue(table.objects.exists()) do_drop_single_stat('to_delete') for table in list(analytics.models.values()): self.assertFalse(table.objects.filter(property='to_delete').exists()) self.assertTrue(table.objects.filter(property='to_save').exists())
Example #2
Source File: views.py From django-idcops with Apache License 2.0 | 6 votes |
def make_state_items(self): state_items = [ { 'model_name': app._meta.model_name, 'verbose_name': app._meta.verbose_name, 'icon': app._meta.icon, 'icon_color': 'bg-' + app._meta.icon_color, 'level': app._meta.level, 'metric': app._meta.metric, 'count': app.objects.filter( onidc=self.request.user.onidc).filter( **app._meta.default_filters).count(), } for app in apps.get_app_config('idcops').get_models() if getattr( app._meta, 'dashboard')] return state_items
Example #3
Source File: sites.py From openhgsenti with Apache License 2.0 | 6 votes |
def app_index(self, request, app_label, extra_context=None): app_dict = self._build_app_dict(request, app_label) if not app_dict: raise Http404('The requested admin page does not exist.') # Sort the models alphabetically within each app. app_dict['models'].sort(key=lambda x: x['name']) app_name = apps.get_app_config(app_label).verbose_name context = dict(self.each_context(request), title=_('%(app)s administration') % {'app': app_name}, app_list=[app_dict], app_label=app_label, ) context.update(extra_context or {}) request.current_app = self.name return TemplateResponse(request, self.app_index_template or [ 'admin/%s/app_index.html' % app_label, 'admin/app_index.html' ], context) # This global object represents the default admin site, for the common case. # You can instantiate AdminSite in your own code to create a custom admin site.
Example #4
Source File: mixins.py From django-idcops with Apache License 2.0 | 6 votes |
def construct_menus(): model_names = [] for app in apps.get_app_config('idcops').get_models(): opts = app._meta if not getattr(opts, 'hidden', False): meta = { 'model_name': opts.model_name, 'verbose_name': opts.verbose_name, 'icon': opts.icon, 'icon_color': 'text-' + opts.icon_color, 'level': opts.level, } model_names.append(meta) counts = list(set([i.get('level') for i in model_names])) new_menus = [] for i in counts: new_menus.append( [c for c in model_names if c.get('level') == i] ) return new_menus
Example #5
Source File: signals.py From django-idcops with Apache License 2.0 | 6 votes |
def initial_user_config(instance, created, **kwargs): if created: models = apps.get_app_config('idcops').get_models() exclude = ['onidc', 'deleted', 'mark'] configures = [] for model in models: fds = [f for f in fields_for_model(model) if f not in exclude] _fields = getattr(model._meta, 'list_display', fds) fields = _fields if isinstance(_fields, list) else fds content = {'list_only_date': 1, 'list_display': fields} config = dict( onidc=instance.onidc, creator=instance, mark='list', content_type=get_content_type_for_model(model), content=json.dumps(content), ) configures.append(Configure(**config)) Configure.objects.bulk_create(configures)
Example #6
Source File: send_slack_notification.py From safe-relay-service with MIT License | 6 votes |
def handle(self, *args, **options): ethereum_client = EthereumClientProvider() app_name = apps.get_app_config('relay').verbose_name network_name = ethereum_client.get_network().name.capitalize() startup_message = f'Starting {app_name} version {__version__} on {network_name}' self.stdout.write(self.style.SUCCESS(startup_message)) if settings.SLACK_API_WEBHOOK: try: r = requests.post(settings.SLACK_API_WEBHOOK, json={'text': startup_message}) if r.ok: self.stdout.write(self.style.SUCCESS(f'Slack configured, "{startup_message}" sent')) else: raise RequestException() except RequestException: self.stdout.write(self.style.ERROR('Cannot send slack notification')) else: self.stdout.write(self.style.SUCCESS('Slack not configured, ignoring'))
Example #7
Source File: fixtures.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def django_sending_elasticapm_client(request, validating_httpserver): validating_httpserver.serve_content(code=202, content="", headers={"Location": "http://example.com/foo"}) client_config = getattr(request, "param", {}) client_config.setdefault("server_url", validating_httpserver.url) client_config.setdefault("service_name", "app") client_config.setdefault("secret_token", "secret") client_config.setdefault("transport_class", "elasticapm.transport.http.Transport") client_config.setdefault("span_frames_min_duration", -1) app = apps.get_app_config("elasticapm.contrib.django") old_client = app.client client = DjangoClient(**client_config) register_handlers(client) instrument(client) app.client = client client.httpserver = validating_httpserver yield client client.close() app.client = old_client if old_client: register_handlers(old_client) instrument(old_client)
Example #8
Source File: fixtures.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def django_elasticapm_client(request): client_config = getattr(request, "param", {}) client_config.setdefault("service_name", "app") client_config.setdefault("secret_token", "secret") client_config.setdefault("span_frames_min_duration", -1) app = apps.get_app_config("elasticapm.contrib.django") old_client = app.client client = TempStoreClient(**client_config) register_handlers(client) instrument(client) app.client = client yield client client.close() app.client = old_client if old_client: register_handlers(old_client) instrument(old_client)
Example #9
Source File: test_apps.py From django-admin-view-permission with BSD 2-Clause "Simplified" License | 6 votes |
def setUp(self): class Meta: permissions = ( ("copy_apptestmodel3", "Can copy apptestmodel3"), ) attrs_1 = { '__module__': 'tests.test_app.models', } attrs_2 = { '__module__': 'tests.test_app.models', 'Meta': Meta, } self.appconfig = apps.get_app_config('test_app') self.model1 = type(str('AppTestModel1'), (models.Model, ), attrs_1.copy()) self.model2 = type(str('AppTestModel2'), (models.Model, ), attrs_1.copy()) self.model3 = type(str('AppTestModel3'), (models.Model, ), attrs_2.copy())
Example #10
Source File: settings.py From elasticsearch-django with MIT License | 6 votes |
def get_index_mapping(index: str) -> dict: """ Return the JSON mapping file for an index. Mappings are stored as JSON files in the mappings subdirectory of this app. They must be saved as {{index}}.json. Args: index: string, the name of the index to look for. """ # app_path = apps.get_app_config('elasticsearch_django').path mappings_dir = get_setting("mappings_dir") filename = "%s.json" % index path = os.path.join(mappings_dir, filename) with open(path, "r") as f: return json.load(f)
Example #11
Source File: test_signals.py From django-test-migrations with MIT License | 6 votes |
def test_signal_receiver_registered_in_test(mocker, signal): """Ensure migration signal receivers registered in tests are called.""" signal_receiver_mock = mocker.MagicMock() main_app_config = apps.get_app_config('main_app') signal.connect( signal_receiver_mock, sender=main_app_config, dispatch_uid=DISPATCH_UID, ) verbosity = 0 interactive = False # call `migrate` management command to trigger ``pre_migrate`` and # ``post_migrate`` signals call_command('migrate', verbosity=verbosity, interactive=interactive) signal_receiver_mock.assert_called_once_with( sender=main_app_config, app_config=main_app_config, apps=mocker.ANY, # we don't have any reference to this object using=DEFAULT_DB_ALIAS, verbosity=verbosity, interactive=interactive, plan=mocker.ANY, # not important for this test signal=signal, )
Example #12
Source File: sites.py From bioforum with MIT License | 6 votes |
def app_index(self, request, app_label, extra_context=None): app_dict = self._build_app_dict(request, app_label) if not app_dict: raise Http404('The requested admin page does not exist.') # Sort the models alphabetically within each app. app_dict['models'].sort(key=lambda x: x['name']) app_name = apps.get_app_config(app_label).verbose_name context = dict( self.each_context(request), title=_('%(app)s administration') % {'app': app_name}, app_list=[app_dict], app_label=app_label, ) context.update(extra_context or {}) request.current_app = self.name return TemplateResponse(request, self.app_index_template or [ 'admin/%s/app_index.html' % app_label, 'admin/app_index.html' ], context) # This global object represents the default admin site, for the common case. # You can instantiate AdminSite in your own code to create a custom admin site.
Example #13
Source File: sites.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def app_index(self, request, app_label, extra_context=None): app_dict = self._build_app_dict(request, app_label) if not app_dict: raise Http404('The requested admin page does not exist.') # Sort the models alphabetically within each app. app_dict['models'].sort(key=lambda x: x['name']) app_name = apps.get_app_config(app_label).verbose_name context = { **self.each_context(request), 'title': _('%(app)s administration') % {'app': app_name}, 'app_list': [app_dict], 'app_label': app_label, **(extra_context or {}), } request.current_app = self.name return TemplateResponse(request, self.app_index_template or [ 'admin/%s/app_index.html' % app_label, 'admin/app_index.html' ], context)
Example #14
Source File: systemviews.py From django-seo with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_view_names(seo_views): output = [] for name in seo_views: try: app = apps.get_app_config(name).models_module except: output.append(name) else: app_name = app.__name__.split(".")[:-1] app_name.append("urls") try: urls = importlib.import_module(".".join(app_name)).urlpatterns except (ImportError, AttributeError): output.append(name) else: for url in urls: if getattr(url, 'name', None): output.append(url.name) return output
Example #15
Source File: options.py From django-seo with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _set_seo_models(self, value): """ Gets the actual models to be used. """ seo_models = [] for model_name in value: if "." in model_name: app_label, model_name = model_name.split(".", 1) model = apps.get_model(app_label, model_name) if model: seo_models.append(model) else: app = apps.get_app_config(model_name) if app: seo_models.extend(app.get_models()) # This fix the trouble on Django 1.9 when django-seo conflicts with session model seo_models = [ model for model in seo_models if model._meta.model_name != 'session' and model._meta.app_label != 'sessions' ] self.seo_models = seo_models
Example #16
Source File: base.py From django-ra-erp with GNU Affero General Public License v3.0 | 6 votes |
def app_index(self, request, app_label, extra_context=None): app_name = apps.get_app_config(app_label).verbose_name context = self.each_context(request) app_list = context['app_list'] current_app_list = get_from_list(False, app_list, 'app_label', app_label) context.update(dict( title=_('%(app)s administration') % {'app': app_name}, # current_app_list=[app_dict], current_app_list=[current_app_list], app_label=app_label, app_name=app_name, )) context.update(extra_context or {}) request.current_app = self.name return TemplateResponse(request, self.app_index_template or [ 'admin/%s/app_index.html' % app_label, 'admin/app_index.html' ], context)
Example #17
Source File: test_counts.py From zulip with Apache License 2.0 | 6 votes |
def test_do_drop_all_analytics_tables(self) -> None: user = self.create_user() stream = self.create_stream_with_recipient()[0] count_args = {'property': 'test', 'end_time': self.TIME_ZERO, 'value': 10} UserCount.objects.create(user=user, realm=user.realm, **count_args) StreamCount.objects.create(stream=stream, realm=stream.realm, **count_args) RealmCount.objects.create(realm=user.realm, **count_args) InstallationCount.objects.create(**count_args) FillState.objects.create(property='test', end_time=self.TIME_ZERO, state=FillState.DONE) analytics = apps.get_app_config('analytics') for table in list(analytics.models.values()): self.assertTrue(table.objects.exists()) do_drop_all_analytics_tables() for table in list(analytics.models.values()): self.assertFalse(table.objects.exists())
Example #18
Source File: test_signals.py From django-test-migrations with MIT License | 6 votes |
def prepare(self): """Connect testing ``pre_migrate`` and ``post_migrate`` receivers.""" self.pre_migrate_receiver_mock = mock.MagicMock() self.post_migrate_receiver_mock = mock.MagicMock() # ``old_apps`` is not real ``ProjectState`` instance, so we cannot use # it to get "original" main_app ``AppConfig`` instance needed to # connect signal receiver, that's the reason we are using # ``apps`` imported directly from ``django.apps`` self.main_app_config = apps.get_app_config('main_app') pre_migrate.connect( self.pre_migrate_receiver_mock, sender=self.main_app_config, ) post_migrate.connect( self.post_migrate_receiver_mock, sender=self.main_app_config, )
Example #19
Source File: sites.py From python with Apache License 2.0 | 6 votes |
def app_index(self, request, app_label, extra_context=None): app_dict = self._build_app_dict(request, app_label) if not app_dict: raise Http404('The requested admin page does not exist.') # Sort the models alphabetically within each app. app_dict['models'].sort(key=lambda x: x['name']) app_name = apps.get_app_config(app_label).verbose_name context = dict( self.each_context(request), title=_('%(app)s administration') % {'app': app_name}, app_list=[app_dict], app_label=app_label, ) context.update(extra_context or {}) request.current_app = self.name return TemplateResponse(request, self.app_index_template or [ 'admin/%s/app_index.html' % app_label, 'admin/app_index.html' ], context) # This global object represents the default admin site, for the common case. # You can instantiate AdminSite in your own code to create a custom admin site.
Example #20
Source File: widgets.py From django-quill with BSD 3-Clause "New" or "Revised" License | 5 votes |
def render(self, name, value, attrs={}): """Render the Quill WYSIWYG.""" if value is None: value = '' final_attrs = self.build_attrs(attrs, name=name) quill_app = apps.get_app_config('quill') quill_config = getattr(quill_app, self.config) return mark_safe(render_to_string(quill_config['template'], { 'final_attrs': flatatt(final_attrs), 'value': value, 'id': final_attrs['id'], 'config': self.config, }))
Example #21
Source File: utils.py From rdmo with Apache License 2.0 | 5 votes |
def set_export_reference_document(format): refdoc_default = apps.get_app_config('rdmo').path + '/share/reference.' + format refdoc = refdoc_default if format == 'odt': try: settings.EXPORT_REFERENCE_ODT except AttributeError: pass else: refdoc = settings.EXPORT_REFERENCE_ODT elif format == 'docx': try: settings.EXPORT_REFERENCE_DOCX except AttributeError: pass else: refdoc = settings.EXPORT_REFERENCE_DOCX if os.path.isfile(refdoc) is False and os.path.isfile(refdoc_default) is True: refdoc = refdoc_default if os.path.isfile(refdoc) is False and os.path.isfile(refdoc_default) is False: refdoc = None return refdoc
Example #22
Source File: loadinitialdata.py From gro-api with GNU General Public License v2.0 | 5 votes |
def load_app_data(self, app_config): if self.apps_loaded.get(app_config.label, False): return if hasattr(app_config, 'data_dependencies'): for dependency in app_config.data_dependencies: self.load_app_data(apps.get_app_config(dependency)) if hasattr(app_config, 'initial_fixture'): call_command( 'loaddata', app_config.initial_fixture, app=app_config.label ) if hasattr(app_config, 'setup_initial_data'): app_config.setup_initial_data() self.apps_loaded[app_config.label] = True
Example #23
Source File: make_theme.py From rdmo with Apache License 2.0 | 5 votes |
def get_folders(self): rdmo_core = os.path.join(apps.get_app_config('rdmo').path, 'core') rdmo_app_theme = os.path.join(os.getcwd(), 'theme') rdmo_app_config = os.path.join(os.getcwd(), 'config', 'settings', 'local.py') return rdmo_core, rdmo_app_theme, rdmo_app_config
Example #24
Source File: asset_filter.py From seal with MIT License | 5 votes |
def ecs_model_choices(model_name, choice_name): asset_app = apps.get_app_config('assets') return getattr(asset_app.get_model(model_name), choice_name)
Example #25
Source File: modules.py From django-admin-tools with MIT License | 5 votes |
def init_with_context(self, context): if self._initialized: return items = self._visible_models(context['request']) apps = {} for model, perms in items: app_label = model._meta.app_label if app_label not in apps: apps[app_label] = { 'title': django_apps.get_app_config(app_label).verbose_name, 'url': self._get_admin_app_list_url(model, context), 'models': [] } model_dict = {} model_dict['title'] = model._meta.verbose_name_plural if perms['change'] or perms.get('view', False): model_dict['change_url'] = self._get_admin_change_url( model, context ) if perms['add']: model_dict['add_url'] = self._get_admin_add_url(model, context) apps[app_label]['models'].append(model_dict) for app in sorted(apps.keys()): # sort model list alphabetically apps[app]['models'].sort(key=lambda x: x['title']) self.children.append(apps[app]) self._initialized = True
Example #26
Source File: wsgi.py From apm-agent-python with BSD 3-Clause "New" or "Revised" License | 5 votes |
def client(self): try: app = apps.get_app_config("elasticapm.contrib.django") return app.client except LookupError: return get_client()
Example #27
Source File: questioner.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def ask_initial(self, app_label): """Should we create an initial migration for the app?""" # If it was specified on the command line, definitely true if app_label in self.specified_apps: return True # Otherwise, we look to see if it has a migrations module # without any Python files in it, apart from __init__.py. # Apps from the new app template will have these; the Python # file check will ensure we skip South ones. try: app_config = apps.get_app_config(app_label) except LookupError: # It's a fake app. return self.defaults.get("ask_initial", False) migrations_import_path, _ = MigrationLoader.migrations_module(app_config.label) if migrations_import_path is None: # It's an application with migrations disabled. return self.defaults.get("ask_initial", False) try: migrations_module = importlib.import_module(migrations_import_path) except ImportError: return self.defaults.get("ask_initial", False) else: # getattr() needed on PY36 and older (replace with attribute access). if getattr(migrations_module, "__file__", None): filenames = os.listdir(os.path.dirname(migrations_module.__file__)) elif hasattr(migrations_module, "__path__"): if len(migrations_module.__path__) > 1: return False filenames = os.listdir(list(migrations_module.__path__)[0]) return not any(x.endswith(".py") for x in filenames if x != "__init__.py")
Example #28
Source File: loader.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def migrations_module(cls, app_label): """ Return the path to the migrations module for the specified app_label and a boolean indicating if the module is specified in settings.MIGRATION_MODULE. """ if app_label in settings.MIGRATION_MODULES: return settings.MIGRATION_MODULES[app_label], True else: app_package_name = apps.get_app_config(app_label).name return '%s.%s' % (app_package_name, MIGRATIONS_MODULE_NAME), False
Example #29
Source File: items.py From django-admin-tools with MIT License | 5 votes |
def init_with_context(self, context): """ Please refer to :meth:`~admin_tools.menu.items.MenuItem.init_with_context` documentation from :class:`~admin_tools.menu.items.MenuItem` class. """ items = self._visible_models(context['request']) apps = {} for model, perms in items: if not (perms['change'] or perms.get('view', False)): continue app_label = model._meta.app_label if app_label not in apps: apps[app_label] = { 'title': django_apps.get_app_config(app_label).verbose_name, 'url': self._get_admin_app_list_url(model, context), 'models': [] } apps[app_label]['models'].append({ 'title': model._meta.verbose_name_plural, 'url': self._get_admin_change_url(model, context) }) for app in sorted(apps.keys()): app_dict = apps[app] item = MenuItem(title=app_dict['title'], url=app_dict['url']) # sort model list alphabetically apps[app]['models'].sort(key=lambda x: x['title']) for model_dict in apps[app]['models']: item.children.append(MenuItem(**model_dict)) self.children.append(item)
Example #30
Source File: context_processors.py From palanaeum with GNU Affero General Public License v3.0 | 5 votes |
def palanaeum_context(request): """ Put all useful information into context, like page title. """ if hasattr(request, 'user') and request.user.is_staff: suggestions = Entry.objects.filter(versions__is_approved=False).distinct().count() suggestions += AudioSource.objects.filter(is_approved=False).count() suggestions += ImageSource.objects.filter(is_approved=False).count() is_staff = True else: suggestions = 0 is_staff = False logo_path = configuration.get_config('logo_file') or static('palanaeum/img/palanaeum_logo.svg') palanaeum_app = apps.get_app_config('palanaeum') return { 'BASE_URL': request.build_absolute_uri("/").rstrip("/"), 'PAGE_TITLE': configuration.get_config('page_title'), 'TINYMCE_API_KEY': settings.TINYMCE_API_KEY, 'GENERAL_SEARCH_PARAM_NAME': search.TextSearchFilter.GET_PARAM_NAME, 'GOOGLE_ID': configuration.get_config('google_analytics'), 'SUGGESTIONS_COUNT': suggestions, 'STAFF': is_staff, 'PALANAEUM_VERSION': settings.PALANAEUM_VERSION, 'PALANAEUM_LOGO_URL': logo_path, 'FAVICON16': favicon(16), 'FAVICON32': favicon(32), 'FAVICON96': favicon(96), 'FAVICON120': favicon(120), 'FAVICON152': favicon(152), 'FAVICON167': favicon(167), 'FAVICON180': favicon(180), 'FAVICON200': favicon(200), 'VERSION_TAG': palanaeum_app.version, }