def allow_migrate(self, db, app_label, model_name=None, **hints): if settings.DATABASES[db].get('PRIMARY', None): return False model_name = model_name or hints.get('model_name') model = hints.get('model') if model: model_name = model.__name__ if not model_name: raise InvalidMigrationException( 'Model name not provided in migration, please pass a `model_name` or `model` with the hints passed into the migration.' ) # Sometimes, when extending models from another app i.e. the User Model, the app label # is the app label of the app where the change is defined but to app with the model is # passed in with the model name. try: app = apps.get_app_config(app_label) model = app.get_model(model_name) except LookupError: app_label = model_name.split('.')[0] app = apps.get_app_config(app_label) model = app.get_model(model_name[len(app_label) + 1:]) single_database = self.get_specific_database_or_none(model) shard_group = self.get_shard_group_if_sharded_or_none(model) if shard_group and single_database: raise InvalidMigrationException( 'Model marked as both sharded and on a single database, unable to determine where to run migrations for {}.'.format(model_name) ) if single_database: return db == single_database if shard_group: return settings.DATABASES[db]['SHARD_GROUP'] == shard_group return db == 'default'
def __init__(self, using=None, allow_self=None, override_role=None, order_by=None, model=None, batch=None, producer=None, **options): super().__init__(**options) self.allow_self = allow_self self.aes_decrypt = aes_decrypt self.deserialize = deserialize self.override_role = override_role self.save = save self.using = using """ Find how inherit parent properties. """ filters = {} if model: filters.update({'tx_name': model}) if batch: filters.update({'batch_id': batch}) if producer: filters.update({'producer': producer}) if filters: try: transactions = IncomingTransaction.objects.filter( **filters).order_by(*order_by.split(',')) self.deserialize_transactions(transactions=transactions) except TransactionDeserializerError as e: raise TransactionDeserializerError(e) from e else: obj = self.file_archiver_cls( src_path=django_apps.get_app_config( 'edc_sync').pending_folder, dst_path=django_apps.get_app_config( 'edc_sync').archive_folder) obj.archive(filename=f'{batch}.json')
def index(request): model1, margin1 = apps.get_app_config('predictor').model1 model2, margin2 = apps.get_app_config('predictor').model2 if request.method == 'POST': form = PredictorForm(request.POST) if form.is_valid(): champions = [int(form.cleaned_data['champ{0}'.format(x)]) for x in range(1, 11)] roles = [int(form.cleaned_data['role{0}'.format(x)]) for x in range(1, 11)] if int(form.cleaned_data['useRoles']) else None if 'predict' in request.POST: from learn import predictWithModel x = predictWithModel(model2 if roles else model1, champions, roles = roles) conf = abs(x) / (margin2 if roles else margin1) arr = ['Low', 'Medium', 'High'] disp = arr[int(conf) - 1] if conf < 4 else 'Very High' return HttpResponse('{0} team is expected to win with {1} confidence ({2:.2f})'.format('Blue' if x > 0 else 'Purple', disp, conf)) elif 'next' in request.POST: from learn import bestNextChamp nextPick = int(form.cleaned_data['nextPick']) x = bestNextChamp(apps.get_app_config('predictor').sc, model2 if roles else model1, nextPick - 1, champions, roles = roles) champMap = championList() x = [champMap[c] for c in x[0]] return HttpResponse('The best champion to pick next is (/is one of) {0}'.format(', '.join(x))) return render(request, 'predictor/index.html', { 'form': PredictorForm() })
def get_models(app_labels): """ Get a list of models for the given app labels, with some exceptions. TODO: If a required model is referenced, it should also be included. Or at least discovered with a get_or_create() call. """ # These models are not to be output, e.g. because they can be generated automatically # TODO: This should be "appname.modelname" string EXCLUDED_MODELS = (ContentType, ) models = [] # If no app labels are given, return all if not app_labels: for app in apps.get_app_configs(): models += [m for m in apps.get_app_config(app.label).get_models() if m not in EXCLUDED_MODELS] return models # Get all relevant apps for app_label in app_labels: # If a specific model is mentioned, get only that model if "." in app_label: app_label, model_name = app_label.split(".", 1) models.append(apps.get_model(app_label, model_name)) # Get all models for a given app else: models += [m for m in apps.get_app_config(app_label).get_models() if m not in EXCLUDED_MODELS] return models
def app_model_error(model_key): try: apps.get_app_config(model_key[0]) model_error = "app '%s' doesn't provide model '%s'" % model_key except LookupError: model_error = "app '%s' isn't installed" % model_key[0] return model_error
def handle(self, *args, **options): # Get the database we're operating from connection = connections[options['database']] # Load up an executor to get all the migration data executor = MigrationExecutor(connection) # Resolve command-line arguments into a migration app_label, migration_name = options['app_label'], options['migration_name'] # Validate app_label try: apps.get_app_config(app_label) except LookupError as err: raise CommandError(str(err)) if app_label not in executor.loader.migrated_apps: raise CommandError("App '%s' does not have migrations" % app_label) try: migration = executor.loader.get_migration_by_prefix(app_label, migration_name) except AmbiguityError: raise CommandError("More than one migration matches '%s' in app '%s'. Please be more specific." % ( migration_name, app_label)) except KeyError: raise CommandError("Cannot find a migration matching '%s' from app '%s'. Is it in INSTALLED_APPS?" % ( migration_name, app_label)) targets = [(app_label, migration.name)] # Show begin/end around output for atomic migrations, if the database # supports transactional DDL. self.output_transaction = migration.atomic and connection.features.can_rollback_ddl # Make a plan that represents just the requested migrations and show SQL # for it plan = [(executor.loader.graph.nodes[targets[0]], options['backwards'])] sql_statements = executor.collect_sql(plan) return '\n'.join(sql_statements)
def extensions(request): content = [] aristotle_apps = getattr(settings, "ARISTOTLE_SETTINGS", {}).get("CONTENT_EXTENSIONS", []) if aristotle_apps: for app_label in aristotle_apps: app = apps.get_app_config(app_label) try: app.about_url = reverse("%s:about" % app_label) except: pass # if there is no about URL, thats ok. content.append(app) content = list(set(content)) aristotle_downloads = getattr(settings, "ARISTOTLE_DOWNLOADS", []) downloads = dict() if aristotle_downloads: for download in aristotle_downloads: app_label = download[3] app_details = downloads.get(app_label, {"app": apps.get_app_config(app_label), "downloads": []}) try: app_details["about_url"] = reverse("%s:about" % app_label) except: pass # if there is no about URL, thats ok. app_details["downloads"].append(download) downloads[app_label] = app_details return render( request, "aristotle_mdr/static/extensions.html", {"content_extensions": content, "download_extensions": downloads}, )
def test_s3_settings(self): """Verify that we enable and configure S3 with a variable""" # Unset, we don't do S3 with mock.patch.dict('os.environ', REQUIRED_SETTINGS, clear=True): settings_vars = self.reload_settings() self.assertNotEqual( settings_vars.get('DEFAULT_FILE_STORAGE'), 'storages.backends.s3boto.S3BotoStorage' ) with mock.patch.dict('os.environ', { **REQUIRED_SETTINGS, '{{ cookiecutter.project_name|upper }}_USE_S3': 'True', }, clear=True), self.assertRaises(ImproperlyConfigured): self.reload_settings() apps.get_app_config('{{ cookiecutter.project_name }}').ready() # Verify it all works with it enabled and configured 'properly' with mock.patch.dict('os.environ', { **REQUIRED_SETTINGS, '{{ cookiecutter.project_name|upper }}_USE_S3': 'True', 'AWS_ACCESS_KEY_ID': '1', 'AWS_SECRET_ACCESS_KEY': '2', 'AWS_STORAGE_BUCKET_NAME': '3', }, clear=True): settings_vars = self.reload_settings() self.assertEqual( settings_vars.get('DEFAULT_FILE_STORAGE'), 'storages.backends.s3boto.S3BotoStorage' )
def create_dynamic_models(self): """ Create models from model definition in models field. Check if model already registered (in case of test run) """ for my_model in self.models: from django.apps import apps if my_model in apps.get_app_config('smyt').get_models(): continue meta = type('Meta', (), {'verbose_name': self.models[my_model]['title'], 'verbose_name_plural': self.models[my_model]['title']}) attrs = {'__module__': self.__module__, '__unicode__': self.set_model_title(my_model), "Meta": meta} for field in self.models[my_model]['fields']: field_variants = { 'char': models.CharField(max_length=255, verbose_name=field['title']), 'int': models.IntegerField(verbose_name=field['title']), 'date': models.DateField(verbose_name=field['title']), } attrs.update({field['id']: field_variants[field['type']]}) try: from django.apps import apps model = apps.get_app_config('smyt').get_model(my_model) yield model except LookupError: model = type(my_model, (models.Model,), attrs) globals()[model.__name__] = model yield model
def handle(self, *args, **options): # We need to execute the post migration callback manually in order # to append the view permission on the proxy model. Then the following # script will create the appropriate content type and move the # permissions under this. If we don't call the callback the script # will create only the basic permissions (add, change, delete) update_permissions( apps.get_app_config('admin_view_permission'), apps.get_app_config('admin_view_permission'), verbosity=1, interactive=True, using='default', ) for model in apps.get_models(): opts = model._meta ctype, created = ContentType.objects.get_or_create( app_label=opts.app_label, model=opts.object_name.lower(), ) for codename, name in get_all_permissions(opts, ctype): perm, created = Permission.objects.get_or_create( codename=codename, content_type=ctype, defaults={'name': name}, ) if created: self.delete_parent_perms(perm) self.stdout.write('Adding permission {}\n'.format(perm))
def app_config_from_namespace(namespace): defaut_namespace = settings.DEFAULT_APP_NAMESPACE app_config = apps.get_app_config(namespace) if not hasattr(app_config, 'manifest') or not app_config.manifest: namespace = defaut_namespace app_config = apps.get_app_config('home_page') return namespace, app_config
def __init__(self, identifier_type=None, template=None, device_id=None, protocol_number=None, site=None, requesting_model=None, identifier=None): self._identifier = None self.requesting_model = requesting_model if not self.requesting_model: raise IdentifierError('Invalid requesting_model. Got None') self.identifier_type = identifier_type or self.identifier_type if not self.identifier_type: raise IdentifierError('Invalid identifier_type. Got None') self.template = template or self.template app_config = django_apps.get_app_config('edc_device') self.device_id = device_id or app_config.device_id app_config = django_apps.get_app_config('edc_protocol') self.protocol_number = protocol_number or app_config.protocol_number self.site = site or Site.objects.get_current() if identifier: # load an existing identifier self.identifier_model = self.identifier_model_cls.objects.get( identifier=identifier) self._identifier = self.identifier_model.identifier self.subject_type = self.identifier_model.subject_type self.site = self.identifier_model.site self.identifier
def save(self, *args, **kwargs): created = not self.pk super(Resource, self).save(*args, **kwargs) self.sync_periodic_task() # This only work on tests (multiprocessing used on real deployments) apps.get_app_config('resources').reload_relations() run('{ sleep 2 && touch %s/wsgi.py; } &' % get_project_dir(), async=True)
def parse_app_labels(revision_manager, app_labels): model_classes = set() if len(app_labels) == 0: for model_class in apps.get_models(): if revision_manager.is_registered(model_class): model_classes.add(model_class) else: for label in app_labels: if "." in label: # This is an app.Model specifier. app_label, model_label = label.split(".") try: app = apps.get_app_config(app_label) except LookupError: raise CommandError("Unknown application: %s" % app_label) try: model_class = app.get_model(model_label) except LookupError: raise CommandError("Unknown model: %s.%s" % (app_label, model_label)) model_classes.add(model_class) else: # This is just an app - no model qualifier. app_label = label try: app = apps.get_app_config(app_label) except LookupError: raise CommandError("Unknown application: %s" % app_label) for model_class in app.get_models(): if revision_manager.is_registered(model_class): model_classes.add(model_class) return model_classes
def get_models(self, options): # Load admin classes. admin.autodiscover() # Get options. app_labels = options["app_label"] # Parse model classes. if len(app_labels) == 0: selected_models = apps.get_models() else: selected_models = set() for label in app_labels: if "." in label: # This is an app.Model specifier. app_label, model_label = label.split(".") try: app = apps.get_app_config(app_label) except LookupError: raise CommandError("Unknown app: {}".format(app_label)) try: model = app.get_model(model_label) except LookupError: raise CommandError("Unknown model: {}.{}".format(app_label, model_label)) selected_models.add(model) else: # This is just an app - no model qualifier. app_label = label try: app = apps.get_app_config(app_label) except LookupError: raise CommandError("Unknown app: {}".format(app_label)) selected_models.update(app.get_models()) for model in selected_models: if is_registered(model): yield model
def extensions(request): content=[] aristotle_apps = getattr(settings, 'ARISTOTLE_SETTINGS', {}).get('CONTENT_EXTENSIONS',[]) if aristotle_apps: for app_label in aristotle_apps: app=apps.get_app_config(app_label) try: app.about_url = reverse('%s:about'%app_label) except: pass # if there is no about URL, thats ok. content.append(app) content = list(set(content)) aristotle_downloads = getattr(settings, 'ARISTOTLE_DOWNLOADS', []) downloads=dict() if aristotle_downloads: for download in aristotle_downloads: app_label = download[3] app_details = downloads.get( app_label, {'app':apps.get_app_config(app_label),'downloads':[]} ) try: app_details['about_url'] = reverse('%s:about'%app_label) except: pass # if there is no about URL, thats ok. app_details['downloads'].append(download) downloads[app_label]=app_details return render(request,"aristotle_mdr/static/extensions.html", {'content_extensions':content,'download_extensions':downloads,} )
def tearDownClass(cls): from django.conf import settings WirecloudRemoteTestCase.tearDownClass.__func__(cls) # Unmock network requests cls.network.unmock_requests() # Remove temporal directory shutil.rmtree(cls.tmp_dir, ignore_errors=True) # deployers catalogue.wgt_deployer = cls.old_catalogue_deployer showcase.wgt_deployer = cls.old_deployer settings.LANGUAGES = cls.old_LANGUAGES settings.LANGUAGE_CODE = cls.old_LANGUAGE_CODE settings.DEFAULT_LANGUAGE = cls.old_DEFAULT_LANGUAGE # Restore old haystack configuration if not cls.use_search_indexes: apps.get_app_config('haystack').signal_processor.setup() else: if not cls.clear_search_indexes: # If self.clear_search_indexes is True, this step is done in a per # test basis in the tearDown method management.call_command('clear_index', interactive=False, verbosity=0) settings.HAYSTACK_CONNECTIONS = cls.old_haystack_conf super(WirecloudSeleniumTestCase, cls).tearDownClass()
def get_apps(application_labels=[], exclude_application_labels=[]): """ - if not @application_labels and not @exclude_application_labels, it returns all applications. - if @application_labels is not None, it returns just these applications, except applications with label in exclude_application_labels. @Returns an array of `module` objects """ if application_labels: applications = [] for app_label in application_labels: if django_greater_than('1.7'): app_config = apps.get_app_config(app_label) applications.append(app_config.module) else: applications.append(models.get_app(app_label)) else: applications = models.get_apps() if exclude_application_labels: for app_label in exclude_application_labels: if app_label: if django_greater_than('1.7'): app_config = apps.get_app_config(app_label) applications.remove(app_config.models_module) else: applications.remove(models.get_app(app_label)) return applications
def test_get_app_config_with_models(self): """ Tests get_app_config(only_with_models_module=True). """ app_config = apps.get_app_config('admin', only_with_models_module=True) self.assertEqual(app_config.name, 'django.contrib.admin') with self.assertRaises(LookupError): apps.get_app_config('staticfiles', only_with_models_module=True)
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update( ambition_subject_dashboard_url_name=django_apps.get_app_config( 'bcpp_clinic_subject').dashboard_url_name, dashboard_url_name=django_apps.get_app_config( self.dashboard_url_app_label).dashboard_url_name, ) return context
def remove_from_cart(request): products = apps.get_app_config('products').models['product'] users = apps.get_app_config('products').models['user'] cart = apps.get_app_config('products').models['cart'] user = users.objects.filter(id=1) product = products.objects.filter(id=request.post['id']) item = cart.filter(user=user, product = product) item.delete()
def _fixture_teardown(self): post_migrate.disconnect(create_default_site, sender=apps.get_app_config('sites')) post_migrate.disconnect(update_contenttypes) post_migrate.disconnect(create_permissions, dispatch_uid="django.contrib.auth.management.create_permissions") super(AskbotTestCase, self)._fixture_teardown() post_migrate.connect(update_contenttypes) post_migrate.connect(create_permissions, dispatch_uid="django.contrib.auth.management.create_permissions") post_migrate.connect(create_default_site, sender=apps.get_app_config('sites'))
def _validate_app_names(self, loader, app_names): has_bad_names = False for app_name in app_names: try: apps.get_app_config(app_name) except LookupError as err: self.stderr.write(str(err)) has_bad_names = True if has_bad_names: sys.exit(2)
def handle(self, *args, **options): if not args: apps = [] for model in a.get_models(): apps.append(a.get_app_config(model._meta.app_label)) else: apps = [] for arg in args: apps.append(a.get_app_config(arg)) for app in apps: create_permissions(app, a.get_models(), options.get('verbosity', 0))
def add_to_cart(request): products = apps.get_app_config('products').models['product'] users = apps.get_app_config('products').models['user'] cart = apps.get_app_config('products').models['cart'] user = users.objects.get(id=1) product = products.objects.get(id=request.POST['id']) entry = cart(user=user, product=product, qty=request.POST['qty']) entry.save() return redirect('/')
def get_models(label): if is_app_or_model(label) == APP: try: app = apps.get_app_config(label) except LookupError as exc: raise ImproperlyConfigured(u'get_models() called for unregistered app %s: %s' % (label, exc)) return app.get_models() else: app_label, model_name = label.split('.') return [apps.get_app_config(app_label).get_model(model_name)]
def test_extension_list_page(self): from django.apps import apps response = self.client.get(reverse('aristotle_mdr:extensions')) self.assertEqual(response.status_code, 200) ext = apps.get_app_config('extension_test') download = apps.get_app_config('text_download_test') self.assertTrue(download.verbose_name in response.content) self.assertTrue('text_download_test' in response.context['download_extensions'].keys()) self.assertTrue(ext.verbose_name in response.content) self.assertTrue(ext in response.context['content_extensions'])
def ready(self): """ App is imported and ready, so bootstrap it. """ from . import receivers as rcvs signals.pre_migrate.connect(rcvs.pre_migrate_receiver, sender=apps.get_app_config('auth')) signals.post_migrate.connect(rcvs.post_migrate_receiver, sender=apps.get_app_config(self.name))
def test_get_app_config(self): """ Tests get_app_config(). """ app_config = apps.get_app_config('admin') self.assertEqual(app_config.name, 'django.contrib.admin') app_config = apps.get_app_config('staticfiles') self.assertEqual(app_config.name, 'django.contrib.staticfiles') with self.assertRaises(LookupError): apps.get_app_config('webdesign')
def test_get_app_config(self): """ Tests get_app_config(). """ app_config = apps.get_app_config("admin") self.assertEqual(app_config.name, "django.contrib.admin") app_config = apps.get_app_config("staticfiles") self.assertEqual(app_config.name, "django.contrib.staticfiles") with self.assertRaises(LookupError): apps.get_app_config("webdesign")
from django.contrib import admin from django.apps import apps, AppConfig # Register your models here. from dj2.settings import dbName as schemaName from main.users_model import users from main.config_model import config try: from main.models import * except: pass # change title admin.site.site_title = schemaName # 设置页面标题 admin.site.site_header = schemaName # 设置网站页头 admin.site.index_title = schemaName # 设置首页标语 allModels = apps.get_app_config('main').get_models() for ind, model in enumerate(allModels): class modelsite(admin.ModelAdmin): list_display = [] for col in model._meta.fields: list_display.append(col.name) search_fields = list_display admin.site.register(model, modelsite)
from django.http.response import HttpResponse from django.utils.decorators import method_decorator from django.views.decorators.cache import never_cache from django.views.generic.base import TemplateView from edc_dashboard.view_mixins import EdcViewMixin from edc_navbar import NavbarViewMixin from django_collect_offline_files.action_handler import ( ActionHandler, ActionHandlerError, ) from ..admin import django_collect_offline_admin from ..offline_view_mixin import OfflineViewMixin from ..site_offline_models import site_offline_models app_config = django_apps.get_app_config("django_collect_offline_files") logger = logging.getLogger("django_collect_offline") @method_decorator(never_cache, name="dispatch") @method_decorator(login_required, name="dispatch") class HomeView(EdcViewMixin, NavbarViewMixin, OfflineViewMixin, TemplateView): template_name = "django_collect_offline/home.html" action_handler_cls = ActionHandler navbar_name = "django_collect_offline" navbar_selected_item = "collect_offline" def __init__(self, **kwargs): super().__init__(**kwargs)
def handle(self, *app_labels, **options): self.verbosity = options['verbosity'] self.interactive = options['interactive'] self.dry_run = options['dry_run'] self.merge = options['merge'] self.empty = options['empty'] self.migration_name = options['name'] if self.migration_name and not self.migration_name.isidentifier(): raise CommandError( 'The migration name must be a valid Python identifier.') self.include_header = options['include_header'] check_changes = options['check_changes'] # Make sure the app they asked for exists app_labels = set(app_labels) has_bad_labels = False for app_label in app_labels: try: apps.get_app_config(app_label) except LookupError as err: self.stderr.write(str(err)) has_bad_labels = True if has_bad_labels: sys.exit(2) # Load the current graph state. Pass in None for the connection so # the loader doesn't try to resolve replaced migrations from DB. loader = MigrationLoader(None, ignore_no_migrations=True) # Raise an error if any migrations are applied before their dependencies. consistency_check_labels = { config.label for config in apps.get_app_configs() } # Non-default databases are only checked if database routers used. aliases_to_check = connections if settings.DATABASE_ROUTERS else [ DEFAULT_DB_ALIAS ] for alias in sorted(aliases_to_check): connection = connections[alias] if (connection.settings_dict['ENGINE'] != 'django.db.backends.dummy' and any( # At least one model must be migrated to the database. router.allow_migrate(connection.alias, app_label, model_name=model._meta.object_name ) for app_label in consistency_check_labels for model in apps.get_app_config(app_label).get_models())): try: loader.check_consistent_history(connection) except OperationalError as error: warnings.warn( "Got an error checking a consistent migration history " "performed for database connection '%s': %s." % (alias, error), RuntimeWarning, ) # Before anything else, see if there's conflicting apps and drop out # hard if there are any and they don't want to merge conflicts = loader.detect_conflicts() # If app_labels is specified, filter out conflicting migrations for unspecified apps if app_labels: conflicts = { app_label: conflict for app_label, conflict in conflicts.items() if app_label in app_labels } if conflicts and not self.merge: name_str = "; ".join("%s in %s" % (", ".join(names), app) for app, names in conflicts.items()) raise CommandError( "Conflicting migrations detected; multiple leaf nodes in the " "migration graph: (%s).\nTo fix them run " "'python manage.py makemigrations --merge'" % name_str) # If they want to merge and there's nothing to merge, then politely exit if self.merge and not conflicts: self.stdout.write("No conflicts detected to merge.") return # If they want to merge and there is something to merge, then # divert into the merge code if self.merge and conflicts: return self.handle_merge(loader, conflicts) if self.interactive: questioner = InteractiveMigrationQuestioner( specified_apps=app_labels, dry_run=self.dry_run) else: questioner = NonInteractiveMigrationQuestioner( specified_apps=app_labels, dry_run=self.dry_run) # Set up autodetector autodetector = MigrationAutodetector( loader.project_state(), ProjectState.from_apps(apps), questioner, ) # If they want to make an empty migration, make one for each app if self.empty: if not app_labels: raise CommandError( "You must supply at least one app label when using --empty." ) # Make a fake changes() result we can pass to arrange_for_graph changes = {app: [Migration("custom", app)] for app in app_labels} changes = autodetector.arrange_for_graph( changes=changes, graph=loader.graph, migration_name=self.migration_name, ) self.write_migration_files(changes) return # Detect changes changes = autodetector.changes( graph=loader.graph, trim_to_apps=app_labels or None, convert_apps=app_labels or None, migration_name=self.migration_name, ) if not changes: # No changes? Tell them. if self.verbosity >= 1: if app_labels: if len(app_labels) == 1: self.stdout.write("No changes detected in app '%s'" % app_labels.pop()) else: self.stdout.write("No changes detected in apps '%s'" % ("', '".join(app_labels))) else: self.stdout.write("No changes detected") else: self.write_migration_files(changes) if check_changes: sys.exit(1)
def get(self, request): plugins = [apps.get_app_config(plugin) for plugin in settings.PLUGINS] return render(request, 'extras/admin/plugins_list.html', { 'plugins': plugins, })
def get_plugin_verbose_name(plugin: str) -> str: """ Returns the verbose name of a plugin. The plugin argument must be a python dotted module path. """ return apps.get_app_config(plugin).verbose_name
from django.utils import timezone from django.utils.cache import add_never_cache_headers, patch_cache_control from django.utils.http import http_date from django.utils.translation import ugettext from django.views.generic import FormView from django.views.generic.base import TemplateView, View from django.views.generic.detail import DetailView from pygments.lexers import get_lexer_for_filename from pygments.util import ClassNotFound from dpaste import highlight from dpaste.forms import SnippetForm, get_expire_values from dpaste.highlight import PygmentsHighlighter from dpaste.models import Snippet config = apps.get_app_config("dpaste") # ----------------------------------------------------------------------------- # Snippet Handling # ----------------------------------------------------------------------------- class SnippetView(FormView): """ Create a new snippet. """ form_class = SnippetForm template_name = "dpaste/new.html" def get(self, request, *args, **kwargs):
def get_context_data(self, **kwargs): model_name = self.kwargs['model_name'] # Get the model class. try: app_config = apps.get_app_config(self.kwargs['app_label']) except LookupError: raise Http404(_("App %(app_label)r not found") % self.kwargs) try: model = app_config.get_model(model_name) except LookupError: raise Http404( _("Model %(model_name)r not found in app %(app_label)r") % self.kwargs) opts = model._meta title, body, metadata = utils.parse_docstring(model.__doc__) title = title and utils.parse_rst(title, 'model', _('model:') + model_name) body = body and utils.parse_rst(body, 'model', _('model:') + model_name) # Gather fields/field descriptions. fields = [] for field in opts.fields: # ForeignKey is a special case since the field will actually be a # descriptor that returns the other object if isinstance(field, models.ForeignKey): data_type = field.remote_field.model.__name__ app_label = field.remote_field.model._meta.app_label verbose = utils.parse_rst( (_("the related `%(app_label)s.%(data_type)s` object") % { 'app_label': app_label, 'data_type': data_type, }), 'model', _('model:') + data_type, ) else: data_type = get_readable_field_data_type(field) verbose = field.verbose_name fields.append({ 'name': field.name, 'data_type': data_type, 'verbose': verbose or '', 'help_text': field.help_text, }) # Gather many-to-many fields. for field in opts.many_to_many: data_type = field.remote_field.model.__name__ app_label = field.remote_field.model._meta.app_label verbose = _("related `%(app_label)s.%(object_name)s` objects") % { 'app_label': app_label, 'object_name': data_type, } fields.append({ 'name': "%s.all" % field.name, "data_type": 'List', 'verbose': utils.parse_rst( _("all %s") % verbose, 'model', _('model:') + opts.model_name), }) fields.append({ 'name': "%s.count" % field.name, 'data_type': 'Integer', 'verbose': utils.parse_rst( _("number of %s") % verbose, 'model', _('model:') + opts.model_name), }) methods = [] # Gather model methods. for func_name, func in model.__dict__.items(): if inspect.isfunction(func) or isinstance(func, property): try: for exclude in MODEL_METHODS_EXCLUDE: if func_name.startswith(exclude): raise StopIteration except StopIteration: continue verbose = func.__doc__ verbose = verbose and (utils.parse_rst( cleandoc(verbose), 'model', _('model:') + opts.model_name)) # Show properties and methods without arguments as fields. # Otherwise, show as a 'method with arguments'. if isinstance(func, property): fields.append({ 'name': func_name, 'data_type': get_return_data_type(func_name), 'verbose': verbose or '' }) elif method_has_no_args(func) and not func_accepts_kwargs( func) and not func_accepts_var_args(func): fields.append({ 'name': func_name, 'data_type': get_return_data_type(func_name), 'verbose': verbose or '', }) else: arguments = get_func_full_args(func) # Join arguments with ', ' and in case of default value, # join it with '='. Use repr() so that strings will be # correctly displayed. print_arguments = ', '.join([ '='.join([arg_el[0], *map(repr, arg_el[1:])]) for arg_el in arguments ]) methods.append({ 'name': func_name, 'arguments': print_arguments, 'verbose': verbose or '', }) # Gather related objects for rel in opts.related_objects: verbose = _("related `%(app_label)s.%(object_name)s` objects") % { 'app_label': rel.related_model._meta.app_label, 'object_name': rel.related_model._meta.object_name, } accessor = rel.get_accessor_name() fields.append({ 'name': "%s.all" % accessor, 'data_type': 'List', 'verbose': utils.parse_rst( _("all %s") % verbose, 'model', _('model:') + opts.model_name), }) fields.append({ 'name': "%s.count" % accessor, 'data_type': 'Integer', 'verbose': utils.parse_rst( _("number of %s") % verbose, 'model', _('model:') + opts.model_name), }) return super().get_context_data( **{ **kwargs, 'name': '%s.%s' % (opts.app_label, opts.object_name), 'summary': title, 'description': body, 'fields': fields, 'methods': methods, })
def migrations_module(cls, app_label): if app_label in settings.MIGRATION_MODULES: return settings.MIGRATION_MODULES[app_label] else: app_package_name = apps.get_app_config(app_label).name return '%s.%s' % (app_package_name, MIGRATIONS_MODULE_NAME)
# -*- coding:utf-8 -*- # Python Module import csv # Django Module from django.apps import apps # Third Party Library # Local Module # Inner Module # Local Model Character = apps.get_app_config('character').get_model('Character') Scenario = apps.get_app_config('scenario').get_model('Scenario') def add_characters(path): """ add characters from csv to db :param path: csv file """ _read_characters(path) def add_scenarios(path): """ add scenario from csv to db :param path: csv file
def get_app_list(context): """ Return a list of all applications Similar to the context `app_list` in index Code taken from contrib/admin/sites.py index() Similar concept in following old link, but in template context processor Disagreed with for overall performance reasons https://djangosnippets.org/snippets/1921/ http://stackoverflow.com/questions/8893755/defining-a-custom-app-list-in-django-admin-index-page :param context :return: list of dictionaries """ app_dict = {} request = context['request'] site = admin.site for model, model_admin in site._registry.items(): app_label = model._meta.app_label has_module_perms = model_admin.has_module_permission(request) if has_module_perms: perms = model_admin.get_model_perms(request) # Check whether user has any perm for this module. # If so, add the module to the model_list. if True in perms.values(): info = (app_label, model._meta.model_name) model_dict = { 'name': capfirst(model._meta.verbose_name_plural), 'object_name': model._meta.object_name, 'perms': perms, } if perms.get('change', False): try: model_dict['admin_url'] = reverse( 'admin:%s_%s_changelist' % info, current_app=site.name) except NoReverseMatch: # pragma: nocover pass if perms.get('add', False): try: model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=site.name) except NoReverseMatch: # pragma: nocover pass if app_label in app_dict: app_dict[app_label]['models'].append(model_dict) else: app_dict[app_label] = { 'name': apps.get_app_config(app_label).verbose_name, 'app_label': app_label, 'app_url': reverse( 'admin:app_list', kwargs={'app_label': app_label}, current_app=site.name, ), 'has_module_perms': has_module_perms, 'models': [model_dict], } # Sort the apps alphabetically. app_list = list(six.itervalues(app_dict)) app_list.sort(key=lambda x: x['name'].lower()) # Sort the models alphabetically within each app. for app in app_list: app['models'].sort(key=lambda x: x['name']) return app_list
from logging import getLogger from django.apps import apps from django.template.defaultfilters import escape, linebreaksbr from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from pygments import highlight from pygments.formatters.html import HtmlFormatter from pygments.lexers import get_lexer_by_name from pygments.lexers.python import PythonLexer from pygments.util import ClassNotFound logger = getLogger(__file__) config = apps.get_app_config('dpaste') # ----------------------------------------------------------------------------- # Highlight Code Snippets # ----------------------------------------------------------------------------- class Highlighter(object): template_name = 'dpaste/highlight/code.html' def highlight(self, code_string, lexer_name=None): """Subclasses need to override this.""" return code_string @staticmethod def get_lexer_display_name(lexer_name, fallback=_('(Deprecated Lexer)')): for l in config.TEXT_FORMATTER + config.CODE_FORMATTER:
def _build_app_dict(self, request, label=None): """ Builds the app dictionary. Takes an optional label parameters to filter models of a specific app. """ app_dict = {} if label: models = { m: m_a for m, m_a in self._registry.items() if m._meta.app_label == label } else: models = self._registry for model, model_admin in models.items(): app_label = model._meta.app_label has_module_perms = model_admin.has_module_permission(request) if not has_module_perms: continue perms = model_admin.get_model_perms(request) # Check whether user has any perm for this module. # If so, add the module to the model_list. if True not in perms.values(): continue info = (app_label, model._meta.model_name) model_dict = { 'name': capfirst(model._meta.verbose_name_plural), 'object_name': model._meta.object_name, 'perms': perms, } if perms.get('change'): try: model_dict['admin_url'] = reverse( 'admin:%s_%s_changelist' % info, current_app=self.name) except NoReverseMatch: pass if perms.get('add'): try: model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=self.name) except NoReverseMatch: pass if app_label in app_dict: app_dict[app_label]['models'].append(model_dict) else: app_dict[app_label] = { 'name': apps.get_app_config(app_label).verbose_name, 'app_label': app_label, 'app_url': reverse( 'admin:app_list', kwargs={'app_label': app_label}, current_app=self.name, ), 'has_module_perms': has_module_perms, 'models': [model_dict], } if label: return app_dict.get(label) return app_dict
def handle(self, *args, **options): """Método invocado internamente pelo Command logo após a validação da passagem de parâmetro. """ # Verificando se o usuário passou o nome da app self._message("Gerando os arquivos da app") # Pagando o nome da App passada por parâmetro app = options['App'] or None if (self._contain_number(app) is False): # Removendo os espaços em branco self.app = app.strip() # Pegando o diretório absoluto atual do projeto. self.path_root = os.getcwd() # Criando o path para a APP informada. self.path_app = os.path.join(self.path_root, app) # Criando o path para a APP Core. self.path_core = os.path.join(self.BASE_DIR, "core") # Criando o path para os models baseado no App informada. self.path_model = os.path.join(self.path_app, "models.py") # Criando o path para os forms baseado na App informada. self.path_form = os.path.join(self.path_app, "forms.py") # Criando o path para as views baseado na App informada. self.path_views = os.path.join(self.path_app, "views.py") # Criando o path para as urls baseado na App informada. self.path_urls = os.path.join(self.path_app, "urls.py") # Criando o path para os serializers baseado na App informada. self.path_serializer = os.path.join(self.path_app, "serializers.py") # Criando o path para o diretório dos templates baseado na App informada. self.path_template_dir = os.path.join(self.path_app, "templates", self.app) # Criando o path para a APP informada. self.path_app = os.path.join(self.path_root, app) # Convertendo os nomes para caracteres minúsculo. # para serem usado nos locais que necessitem dos nomes # em minúsculo. self.app_lower = app.lower() # Verificando se o diretório da App informada existe if self._check_dir(self.path_app) is False: self._message("Diretório não encontrado.") return # Verifica se app esta instalada, pois precisa dela # para recuperar as instancias dos models if apps.is_installed(self.app_lower) is False: self._message( "Você deve colocar sua app no INSTALLED_APPS do settings.") return #Criando uma instancia da app self.app_instance = apps.get_app_config(self.app_lower) #Verificando se o usuário passou o nome do model if options['Model']: model = options['Model'] or None if (self._contain_number(model) is False): # Removendo os espaços em branco self.model = model.strip() # Verificando se existe no models.py o Model informado if self._check_content(self.path_model, 'class {}'.format( self.model)) is False: self._message("Model informado não encontrado.") return try: # Verifica se o model está na app informada # Se o model for abstract ela retornará uma exceção LookupError self.app_instance.get_model(self.model) self._message("Gerando arquivos para o model {}".format( self.model)) # Convertendo os nomes para caracteres minúsculo. # para serem usado nos locais que necessitem dos nomes # em minúsculo. self.model_lower = model.lower() self.call_methods(options) self._message("Processo concluído.") except LookupError: self._message( "Esse model é abastrato. Não vão ser gerados os arquivos." ) else: # recupera todos os models da app for model in self.app_instance.get_models(): model = model.__name__ # Removendo os espaços em branco self.model = model.strip() self._message("Gerando arquivos para o model {}".format( self.model)) # Convertendo os nomes para caracteres minúsculo. # para serem usado nos locais que necessitem dos nomes # em minúsculo. self.model_lower = model.lower() #Chama os métodos de geração de arquivos self.call_methods(options) self._message("Processo concluído para o model {}.".format( self.model)) self._message("Processo concluído.") return
K_CAP = getattr(settings, 'ANYCLUSTER_K_CAP', 30) # get the model as defined in settings geoapp, geomodel = settings.ANYCLUSTER_GEODJANGO_MODEL.split('.') geo_column_str = settings.ANYCLUSTER_COORDINATES_COLUMN # column for determining the pin image for pins with count 1 PINCOLUMN = getattr(settings, 'ANYCLUSTER_PINCOLUMN', None) # raw sql for getting pin column value if PINCOLUMN: pin_qry = [', MIN(%s) AS pinimg' % (PINCOLUMN), PINCOLUMN + ','] else: pin_qry = ['', ''] app_config = apps.get_app_config(geoapp) Gis = app_config.get_model(geomodel) geo_table = Gis._meta.db_table class MapClusterer(): def __init__(self, request, zoom=1, gridSize=256, input_srid=4326, mapTileSize=256): # the srid of the coordinates coming from javascript. input_srid = output_srid self.input_srid = int(input_srid)
def get_annotation_model(): app_name, model_name = ANNOTATION_MODEL_NAME.split(".") app = apps.get_app_config(app_name) return app.get_model(model_name)
def test_checkout_apps(self): self.assertEqual(FeedConfig.name, 'feed') self.assertEqual(apps.get_app_config('feed').name, 'feed')
def test_core_config(self): self.assertEqual(apps.get_app_config('core').name, 'core')
from edc_reference.site_reference import site_reference_configs from edc_utils import get_utcnow from edc_visit_schedule.site_visit_schedules import site_visit_schedules from edc_visit_tracking.constants import SCHEDULED from faker import Faker from edc_metadata import KEYED, NOT_REQUIRED, REQUIRED from edc_metadata.models import CrfMetadata from ...metadata_rules import CrfRule, CrfRuleGroup, P, site_metadata_rules from ..models import Appointment, CrfOne, CrfTwo, SubjectConsent, SubjectVisit from ..reference_configs import register_to_site_reference_configs from ..visit_schedule import visit_schedule fake = Faker() edc_registration_app_config = django_apps.get_app_config("edc_registration") class CrfRuleGroupOne(CrfRuleGroup): crfs_car = CrfRule( predicate=P("f1", "eq", "car"), consequence=REQUIRED, alternative=NOT_REQUIRED, target_models=["crftwo"], ) crfs_bicycle = CrfRule( predicate=P("f3", "eq", "bicycle"), consequence=REQUIRED, alternative=NOT_REQUIRED,
def get_model(s): app_label, model_name = s.split(".") return apps.get_app_config(app_label).get_model(model_name)
@admin.register(Event) class EventAdmin(admin.ModelAdmin): form = EventForm ordering = ('-start_date', ) class ContentInline(admin.TabularInline): model = Content ordering = ('ordering', ) fields = ('type', 'hypertext') extra = 0 @admin.register(Action) class ActionAdmin(admin.ModelAdmin): inlines = (ContentInline, ) @admin.register(Post) class PostAdmin(admin.ModelAdmin): model = Post raw_id_fields = ('organization', ) for model in apps.get_app_config("decisions").get_models(): try: admin.site.register(model) except admin.sites.AlreadyRegistered: pass
from .models import User from django.apps import apps SCORE_RANGE = apps.get_app_config('intervalsApp').SCORE_RANGE def handle_answer(user: User, correct): current_user = user.profile recent_results = current_user.recent_results_at_level( current_user.current_level) # Update user model based on correctness if correct: recent_results.total_correct += 1 recent_results.total_completed += 1 # Cycle list data structure to contain most recent results if len(recent_results.recent_results) >= SCORE_RANGE: recent_results.recent_results.pop(0) recent_results.recent_results.append(True) else: recent_results.total_completed += 1 # Cycle list data structure to contain most recent results if len(recent_results.recent_results) >= SCORE_RANGE: recent_results.recent_results.pop(0) recent_results.recent_results.append(False) # Level up user logic # If level being done is user's level if current_user.level == current_user.current_level:
from django.contrib.auth import get_user_model from django.contrib.auth.management import create_permissions from django.contrib.auth.models import Group, Permission, AnonymousUser from django.contrib.contenttypes.models import ContentType from django.test import TestCase from guardian.core import ObjectPermissionChecker from guardian.exceptions import NotUserNorGroup from guardian.models import UserObjectPermission, GroupObjectPermission from guardian.shortcuts import assign_perm from guardian.management import create_anonymous_user from guardian.utils import evict_obj_perms_cache from guardian.testapp.models import Project, ProjectUserObjectPermission, ProjectGroupObjectPermission auth_app = django_apps.get_app_config('auth') User = get_user_model() class CustomUserTests(TestCase): def test_create_anonymous_user(self): create_anonymous_user(object(), using='default') self.assertEqual(1, User.objects.all().count()) anonymous = User.objects.all()[0] self.assertEqual(anonymous.username, guardian_settings.ANONYMOUS_USER_NAME) class ObjectPermissionTestCase(TestCase): def setUp(self): self.group, created = Group.objects.get_or_create(name='jackGroup')
def file_not_found_image_path(self): app_config = apps.get_app_config('baseapp') return os.path.join(app_config.path, 'static', FILE_NOT_FOUND_IMAGE)
def test_apps(self): self.assertEqual(ShafiyaPinjamConfig.name, 'shafiya_pinjam') self.assertEqual(apps.get_app_config( 'shafiya_pinjam').name, 'shafiya_pinjam')
def get(self, request, format=None): return Response([self._get_plugin_data(apps.get_app_config(plugin)) for plugin in settings.PLUGINS])
from django.apps import apps from django.contrib import admin app = apps.get_app_config("virtualization") for model_name, model in app.models.items(): try: admin.site.register(model) except admin.sites.AlreadyRegistered: pass
from django.views.decorators.http import require_http_methods from django.views.decorators.gzip import gzip_page from django.apps import apps from django.urls import reverse from django.http import QueryDict, Http404 from legal.common.glob import REGISTERS, INERR, TEXT_OPTS_KEYS, REPO_URL, EXLIM_TITLE, LOCAL_SUBDOMAIN, LOCAL_URL, DTF from legal.common.utils import Pager, new_xml, xml_decorate, composeref, LOGGER, render from legal.szr.glob import SUPREME_ADMINISTRATIVE_COURT, SUPREME_ADMINISTRATIVE_COURT_NAME from legal.udn.forms import MainForm from legal.udn.models import Agenda, Decision APP = __package__.rpartition('.')[2] APPVERSION = apps.get_app_config(APP).version BATCH = 50 REPO_PREFIX = join(REPO_URL, APP) EXLIM = 1000 @require_http_methods(('GET', 'POST')) def mainpage(request): LOGGER.debug('Main page accessed using method {}'.format(request.method), request, request.POST) err_message = '' page_title = apps.get_app_config(APP).verbose_name
def handle(self, *app_labels, **options): self.verbosity = int(options.get('verbosity')) self.interactive = options.get('interactive') self.dry_run = options.get('dry_run', False) self.merge = options.get('merge', False) self.empty = options.get('empty', False) # Make sure the app they asked for exists app_labels = set(app_labels) bad_app_labels = set() for app_label in app_labels: try: apps.get_app_config(app_label) except LookupError: bad_app_labels.add(app_label) if bad_app_labels: for app_label in bad_app_labels: self.stderr.write("App '%s' could not be found. Is it in INSTALLED_APPS?" % app_label) sys.exit(2) # Load the current graph state. Pass in None for the connection so # the loader doesn't try to resolve replaced migrations from DB. loader = MigrationLoader(None, ignore_no_migrations=True) # Before anything else, see if there's conflicting apps and drop out # hard if there are any and they don't want to merge conflicts = loader.detect_conflicts() # If app_labels is specified, filter out conflicting migrations for unspecified apps if app_labels: conflicts = dict( (app_label, conflict) for app_label, conflict in iteritems(conflicts) if app_label in app_labels ) if conflicts and not self.merge: name_str = "; ".join( "%s in %s" % (", ".join(names), app) for app, names in conflicts.items() ) raise CommandError("Conflicting migrations detected (%s).\nTo fix them run 'python manage.py makemigrations --merge'" % name_str) # If they want to merge and there's nothing to merge, then politely exit if self.merge and not conflicts: self.stdout.write("No conflicts detected to merge.") return # If they want to merge and there is something to merge, then # divert into the merge code if self.merge and conflicts: return self.handle_merge(loader, conflicts) # Set up autodetector autodetector = MigrationAutodetector( loader.project_state(), ProjectState.from_apps(apps), InteractiveMigrationQuestioner(specified_apps=app_labels, dry_run=self.dry_run), ) # If they want to make an empty migration, make one for each app if self.empty: if not app_labels: raise CommandError("You must supply at least one app label when using --empty.") # Make a fake changes() result we can pass to arrange_for_graph changes = dict( (app, [Migration("custom", app)]) for app in app_labels ) changes = autodetector.arrange_for_graph(changes, loader.graph) self.write_migration_files(changes) return # Detect changes changes = autodetector.changes( graph=loader.graph, trim_to_apps=app_labels or None, convert_apps=app_labels or None, ) # No changes? Tell them. if not changes and self.verbosity >= 1: if len(app_labels) == 1: self.stdout.write("No changes detected in app '%s'" % app_labels.pop()) elif len(app_labels) > 1: self.stdout.write("No changes detected in apps '%s'" % ("', '".join(app_labels))) else: self.stdout.write("No changes detected") return self.write_migration_files(changes)
def setUp(self): self._original_permissions = Permission._meta.permissions[:] self._original_default_permissions = Permission._meta.default_permissions self.app_config = apps.get_app_config('auth')
def get_nav_menu(self): site_menu = list(self.get_site_menu() or []) had_urls = [] def get_url(menu, had_urls): if 'url' in menu: had_urls.append(menu['url']) if 'menus' in menu: for m in menu['menus']: get_url(m, had_urls) get_url({'menus': site_menu}, had_urls) nav_menu = OrderedDict() for model, model_admin in self.admin_site._registry.items(): if getattr(model_admin, 'hidden_menu', False): continue app_label = model._meta.app_label app_icon = None model_dict = { 'title': unicode(capfirst(model._meta.verbose_name_plural)), 'url': self.get_model_url(model, "changelist"), 'icon': self.get_model_icon(model), 'perm': self.get_model_perm(model, 'view'), 'order': model_admin.order, } if model_dict['url'] in had_urls: continue app_key = "app:%s" % app_label if app_key in nav_menu: nav_menu[app_key]['menus'].append(model_dict) else: # Find app title app_title = unicode(app_label.title()) if app_label.lower() in self.apps_label_title: app_title = self.apps_label_title[app_label.lower()] else: app_title = unicode(apps.get_app_config(app_label).verbose_name) #find app icon if app_label.lower() in self.apps_icons: app_icon = self.apps_icons[app_label.lower()] nav_menu[app_key] = { 'title': app_title, 'menus': [model_dict], } app_menu = nav_menu[app_key] if app_icon: app_menu['first_icon'] = app_icon elif ('first_icon' not in app_menu or app_menu['first_icon'] == self.default_model_icon) and model_dict.get('icon'): app_menu['first_icon'] = model_dict['icon'] if 'first_url' not in app_menu and model_dict.get('url'): app_menu['first_url'] = model_dict['url'] for menu in nav_menu.values(): menu['menus'].sort(key=sortkeypicker(['order', 'title'])) nav_menu = nav_menu.values() nav_menu.sort(key=lambda x: x['title']) site_menu.extend(nav_menu) return site_menu