def test_custom_user(self): """ Regression test for #22325 - references to a custom user model defined in the same app are not resolved correctly. """ executor = MigrationExecutor(connection) self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble") # Migrate forwards executor.migrate([("migrations", "0001_initial")]) self.assertTableExists("migrations_author") self.assertTableExists("migrations_tribble") # Make sure the soft-application detection works (#23093) # Change table_names to not return auth_user during this as # it wouldn't be there in a normal run, and ensure migrations.Author # exists in the global app registry temporarily. old_table_names = connection.introspection.table_names connection.introspection.table_names = lambda c: [x for x in old_table_names(c) if x != "auth_user"] migrations_apps = executor.loader.project_state(("migrations", "0001_initial")).apps global_apps.get_app_config("migrations").models["author"] = migrations_apps.get_model("migrations", "author") try: migration = executor.loader.get_migration("auth", "0001_initial") self.assertEqual(executor.detect_soft_applied(None, migration)[0], True) finally: connection.introspection.table_names = old_table_names del global_apps.get_app_config("migrations").models["author"] # And migrate back to clean up the database executor.loader.build_graph() executor.migrate([("migrations", None)]) self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble")
def test_custom_user(self): """ Regression test for #22325 - references to a custom user model defined in the same app are not resolved correctly. """ executor = MigrationExecutor(connection) self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble") # Migrate forwards executor.migrate([("migrations", "0001_initial")]) self.assertTableExists("migrations_author") self.assertTableExists("migrations_tribble") # Make sure the soft-application detection works (#23093) # Change get_table_list to not return auth_user during this as # it wouldn't be there in a normal run, and ensure migrations.Author # exists in the global app registry temporarily. old_get_table_list = connection.introspection.get_table_list connection.introspection.get_table_list = lambda c: [x for x in old_get_table_list(c) if x != "auth_user"] migrations_apps = executor.loader.project_state(("migrations", "0001_initial")).render() global_apps.get_app_config("migrations").models["author"] = migrations_apps.get_model("migrations", "author") try: migration = executor.loader.get_migration("auth", "0001_initial") self.assertEqual(executor.detect_soft_applied(migration), True) finally: connection.introspection.get_table_list = old_get_table_list del global_apps.get_app_config("migrations").models["author"] # And migrate back to clean up the database executor.loader.build_graph() executor.migrate([("migrations", None)]) self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble")
def prikaz_plugin(request, id): """ Postavlja novi plugin za prikaz Parameters ------- request : HttpRequest http zahtev za pocetnu stranicu id : string identifikator novog plugina za prikaz Returns ------- odgovor : HttpRedirect preusmerava na prikaz """ request.session['izabran_plugin_prikaz'] = id apps.get_app_config('core_module').select_view_plugin(id, request) plug_viz = apps.get_app_config('core_module').selected_view_plugin director = apps.get_app_config('core_module').director builder = TemplateBuilder(plug_viz) template = director.buildTemplate(builder) with open("..//Core//core_module//templates//Output.html", "w") as text_file: text_file.write(template) return redirect('prikaz_komponenta')
def prikaz_komponenta(request): """ Prikazivanje ucitanih podataka Parameters ------- request : HttpRequest http zahtev za prikaz Returns ------- odgovor : HttpResponse vraca http odgovor koji ce u browseru prikazati ucitane podatke ukoliko oni postoje i plugin koji ce ih prikazati """ plugini = apps.get_app_config('core_module').plugini_ucitavanje plugini_prikaz = apps.get_app_config('core_module').plugini_prikaz plug_viz = apps.get_app_config('core_module').selected_view_plugin # ako ne postoji plugin za prikaz # napravi prazan template if plug_viz is None: template = "{% extends 'prikaz_komponenta.html' %} \n" \ "{% block head_sadrzaj %}\n" \ "{% endblock %} {% block component %} {% endblock %}" with open("..//Core//core_module//templates//Output.html", "w") as text_file: text_file.write(template) return render(request, "Output.html", {"title": "GraphVizz", "plugini_ucitavanje": plugini, "plugini_prikaz": plugini_prikaz, "nodes": Node.objects.all()})
def test_settings_check(settings): assert len(check_required_settings_defined(apps.get_app_config("modernrpc"))) == 0 settings.MODERNRPC_METHODS_MODULES = [] result = check_required_settings_defined(apps.get_app_config("modernrpc")) assert len(result) == 1 assert result[0].id == 'modernrpc.E001'
def utilize_plugins(request): plugins_initialized = apps.get_app_config('Core_Component').list_of_plugins countries_plugin = None for plugin in plugins_initialized: if plugin.EntryPointName() == "Countries": countries_plugin = plugin path = request.POST.get("path") apps.get_app_config( 'Core_Component').graph = countries_plugin.load_countries(path) return redirect('landing_page')
def test_settings_check(settings): # With default testsite.settings, check method shouldn't complain assert len( check_required_settings_defined(apps.get_app_config("modernrpc"))) == 0 # After deleting values in settings.MODERNRPC_METHODS_MODULES, the check should warn settings.MODERNRPC_METHODS_MODULES = [] result = check_required_settings_defined(apps.get_app_config("modernrpc")) assert len(result) == 1 assert result[0].id == 'modernrpc.E001'
def index(request): plugini = apps.get_app_config('d3_primeri').plugini_ucitavanje plugini_viz = apps.get_app_config('d3_primeri').plugini_vizualizatori nodes = Node.objects.all() return render( request, "index.html", { "title": "Index", "plugini_ucitavanje": plugini, "plugini_vizualizatori": plugini_viz, "node_data": nodes, "nodes_id": [] })
def landing_page(request): load_plugins = apps.get_app_config('Core_Component').list_of_plugins flag = apps.get_app_config('Core_Component').flag graph = apps.get_app_config('Core_Component').graph graph_f_c = apps.get_app_config('Core_Component').graph_for_continents context_variables = { "title": "Graph Vizualization", "load_plugins": load_plugins, "graph": graph, "flag": flag, "g_f_c": graph_f_c } return render(request, 'base.html', context_variables)
def filter(request): id = request.session['izabran_plugin_viz'] plugini = apps.get_app_config('d3_primeri').plugini_ucitavanje plugini_viz = apps.get_app_config('d3_primeri').plugini_vizualizatori all_nodes = Node.objects.all() root = all_nodes[0] #root je prvi node u bazi tree = {} abspath = os.path.abspath("") root_path = abspath[:-14] content_path = root_path + "D3Core\\d3_primeri\\templates\\content.html" links_path = root_path + "D3Core\\d3_primeri\\templates\\links_template.html" nodes_path = root_path + "D3Core\\d3_primeri\\templates\\nodes_template.html" file_content = open(content_path, 'w') file_nodes = open(nodes_path, 'w') file_links = open(links_path, 'w') filter_text = "" nodes_id = [] if request.method == 'POST': filter_text = request.POST['filter_text'] print(filter_text) nodes_id = refreshTree(filter_text) print(nodes_id) filteredNodes = getFilteredNodes(filter_text) apps.get_app_config('d3_primeri').stavi_aktivan_plugin_viz(id) plugin = apps.get_app_config('d3_primeri').aktivan_viz tree = plugin.getTree() nodesHTML = plugin.getHTMLNodes() linksHTML = plugin.getHTMLLinks() contentHTML = plugin.getHTMLContent(filteredNodes) file_nodes.write(nodesHTML) file_nodes.close() file_links.write(linksHTML) file_links.close() file_content.write(contentHTML) file_content.close() return render( request, "content.html", { "title": "Filter", "plugini_ucitavanje": plugini, "plugini_vizualizatori": plugini_viz, "tree": None, "root": None, "nodes": filteredNodes, "node_data": filteredNodes, "nodes_id": [] })
def uploadData(request): try: if request.method == 'POST' and request.FILES['file']: dataFile = request.FILES['file'] dataFile = dataFile.read().decode('ansi', 'strict') graph = deserialize(dataFile) apps.get_app_config('Core').graph = graph return redirect('/core/visualization') except MultiValueDictKeyError: graph = Graph() apps.get_app_config('Core').graph = graph return redirect('/core/visualization')
def prikazati(self, request): plugini = apps.get_app_config('d3_primeri').plugini_ucitavanje plugini1 = apps.get_app_config('d3_primeri').plugini_prikaz elementi = Element.objects.all() atributi = Attribute.objects.all() linkovi = Link.objects.all() return render(request, "jednostavanPrikaz.html", {"title": "Jednostavan prikaz", "plugini_ucitavanje": plugini, "plugini_prikazivanje": plugini1, "elementi": elementi, "atributi": atributi, "linkovi": linkovi})
def search_country(request): name = request.POST.get("country") if name is None: return redirect('landing_page') load_plugins = apps.get_app_config('Core_Component').list_of_plugins g_f_c = apps.get_app_config('Core_Component').graph_for_continents for v in g_f_c.outgoing: v.element.found = False graph = apps.get_app_config('Core_Component').graph try: response = tree_layout(request, g_f_c, name, load_plugins, graph) return response except: return redirect('landing_page')
def force_layout_slozen(self, request): plugini = apps.get_app_config('d3_primeri').plugini_ucitavanje plugini1 = apps.get_app_config('d3_primeri').plugini_prikaz elementi = Element.objects.all() atributi = Attribute.objects.all() linkovi = Link.objects.all() return render(request, "forceSlozenPrikaz.html", {"title": "Slozen prikaz prikaz", "plugini_ucitavanje": plugini, "plugini_prikazivanje": plugini1, "elementi": elementi, "atributi": atributi, "linkovi": linkovi})
def ucitavanje_plugin(request, id): request.session['izabran_plugin_ucitavanje'] = id plugini = apps.get_app_config('d3_primeri').plugini_ucitavanje Node.objects.all().delete() Attribute.objects.all().delete() Link.objects.all().delete() putanja_izvora = "" if request.method == 'POST': print(request.POST) putanja_izvora = request.POST['putanja_izvora'] apps.get_app_config('d3_primeri').stavi_aktivan_plugin_ucitavanje(id) plugin = apps.get_app_config('d3_primeri').aktivan_ucitavanje plugin.ucitati(putanja_izvora) print("ucitavanje_plugin(request,id,path) ", putanja_izvora) return redirect('index')
def dobavi_podatke(request): """ Vraca ucitane podatke Parameters ------- request : HttpRequest http zahtev Returns ------- odgovor : JsonResponse JSON datoteka sa strukturom grafa (nodes, links) format : { nodes : [{id, name, influence, group, bold (da li je selektovan cvor), attributes: [{ node_id, name, value }] }, links : [{id, source_id, target_weight, weight }] } """ if len(apps.get_app_config('core_module').plugini_ucitavanje) == 0: return JsonResponse({}) if 'plugin_prikaz_ime' not in request.session.keys(): return JsonResponse({}) if 'plugin_ucitavanje_ime' not in request.session.keys(): return JsonResponse({}) nodes = list(Node.objects.values()) for node in nodes: x = Attribute.objects.filter(node_id=node['id']) node['attributes'] = list(x.values()) links = list(Link.objects.values()) #print(request.session['plugin_prikaz_ime']) return JsonResponse({"nodes": nodes, "links": links})
def audit_view(request, model_admin): show_tech = request.GET.get('show_tech') == 'true' if show_tech: log = combined_recent( limit=settings.AUDIT_LOG_SIZE, threadlike=ThreadLike.objects.all(), thread=Thread.objects.all(), comment=Post.objects.all(), ) else: log = combined_recent( limit=settings.AUDIT_LOG_SIZE, threadlike=ThreadLike.objects.exclude(user_id=settings.TECH_USER), thread=Thread.objects.exclude(user_id=settings.TECH_USER), comment=Post.objects.exclude(user_id=settings.TECH_USER), ) opts = model_admin.model._meta app_config = apps.get_app_config(opts.app_label) context = { **model_admin.admin_site.each_context(request), "opts": opts, "app_config": app_config, "results": log, "show_tech": show_tech } template_name = "admin/askapp/audit.html" return render(request, template_name, context)
def get_all_models(app_label=None): """Returns all model classes of all apps, including registered abstract ones. The resulting data structure is a dictionary which maps the class names to the model classes. Note that every app must have a ``models.py`` module. This ``models.py`` may be empty, though. :param app_label: the name of the app whose models should be returned :type app_label: unicode :return: all models of all apps :rtype: dict mapping str to ``class`` """ global all_models, abstract_models if app_label: result = dict((model.__name__, model) for model in apps.get_app_config(app_label).get_models()) result.update((model.__name__, model) for model in abstract_models if model._meta.app_label == app_label) return result if all_models is None: abstract_models = frozenset(abstract_models) all_models = dict( (model.__name__, model) for model in apps.get_models()) all_models.update((model.__name__, model) for model in abstract_models) return all_models.copy()
def get_models(app_mod=None, include_auto_created=False): """Return the models belonging to an app. Args: app_mod (module, optional): The application module. include_auto_created (bool, optional): Whether to return auto-created models (such as many-to-many models) in the results. Returns: list: The list of modules belonging to the app. """ if apps: # Django >= 1.7 if app_mod is None: return apps.get_models(include_auto_created=include_auto_created) else: app_label = app_mod.__name__.split('.')[-2] try: app_config = apps.get_app_config(app_label) return [ model for model in app_config.get_models( include_auto_created=include_auto_created) if not model._meta.abstract ] except LookupError: return [] else: # Django < 1.7 return _get_models(app_mod, include_auto_created=include_auto_created)
def lista_kategorija(request): kategorije = Kategorija.objects.all() title = apps.get_app_config('prodavnice').verbose_name return render(request, "lista_kategorija.html", { "title": title, "kategorije": kategorije })
def database_forwards(self, app_label, schema_editor, from_state, to_state): fake_model = self.get_fake_model(app_label, from_state) # We now need the real model, the problem is that the __fake__ model doesn't have access # to anything else (functions / properties) than the Fields # So to access the model.tenant_id, we need this. app = global_apps.get_app_config( fake_model._meta.app_label if fake_model else app_label) self.model = None for model in app.get_models(): if model.__name__ == self.model_name: self.model = model if fake_model and not self.model: # The model has been deleted # We can't distribute that table as we don't have the initial model anymore # So no idea what the tenant column is # However, as there are create foreign key constraints that will fail in further migrations # We need to make it a reference table self.reference = True self.args = [fake_model._meta.db_table] if not self.reference: self.args.append(get_tenant_column(self.model)) schema_editor.execute(self.get_query(), params=self.args)
def ucitavanje_plugin(request, id): request.session['izabran_plugin_ucitavanje'] = id plugini = apps.get_app_config('d3_primeri').plugini_ucitavanje for i in plugini: if i.identifier() == id: i.ucitati() return redirect('index')
def ucitavanje_plugin(request, id, parameters=""): """ Postavlja novi plugin za ucitavanje Parameters ------- request : HttpRequest http zahtev za pocetnu stranicu id : string identifikator novog plugina za prikaz parameters : dictionary recnik sa parametrima forme (ukoliko plugin ima te parametre) Returns ------- odgovor : HttpRedirect preusmerava na pocetnu stranicu """ request.session['izabran_plugin_ucitavanje'] = id plugini = apps.get_app_config('core_module').plugini_ucitavanje for i in plugini: if i.identifier() == id: request.session['plugin_ucitavanje_ime'] = i.naziv() i.ucitati(parameters) return redirect('/')
def _build_app_dict(self, reqeust, label=None): """ :param reqeust: :param label: :return: 获取 1、已注册的app 2、app下的model名称 3、model对应的url """ app_dict = {} models = self._registry for model, model_admin in models.items(): app_label = model._meta.app_label info = (app_label, model._meta.model_name) model_dict = { 'name': capfirst(model._meta.verbose_name_plural), 'object_name': model._meta.object_name, 'myadmin_url': 'myadmin_{}_{}'.format(app_label, model._meta.model_name) } 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, 'models': [model_dict] } return app_dict
def test_init_registry_cleaning(settings): orig_modules_list = settings.MODERNRPC_METHODS_MODULES app = apps.get_app_config("modernrpc") app.ready() # Retrieve all methods defined in custom modules (minus system.* methods) custom_rpc_methods = [m for m in get_all_method_names() if not m.startswith('system.')] # Ensure a normal init registered some rpc methods assert len(custom_rpc_methods) > 0 # Re-init library, with only invalid module as "methods module" settings.MODERNRPC_METHODS_MODULES = ['nope'] # This will ensure a warning is thrown, due to invalid module specified with pytest.warns(Warning): app.ready() # Now, we should have removed all custom methods from the registry custom_rpc_methods = [m for m in get_all_method_names() if not m.startswith('system.')] assert len(custom_rpc_methods) == 0 # Re-init library, with None modules list settings.MODERNRPC_METHODS_MODULES = None app.ready() custom_rpc_methods = [m for m in get_all_method_names() if not m.startswith('system.')] assert len(custom_rpc_methods) == 0 # Restore original state for registry settings.MODERNRPC_METHODS_MODULES = orig_modules_list app.ready()
def __init__(self, real_apps, models, ignore_swappable=False): # Any apps in self.real_apps should have all their models included # in the render. We don't use the original model instances as there # are some variables that refer to the Apps object. # FKs/M2Ms from real apps are also not included as they just # mess things up with partial states (due to lack of dependencies) self.real_models = [] for app_label in real_apps: app = global_apps.get_app_config(app_label) for model in app.get_models(): self.real_models.append(ModelState.from_model(model, exclude_rels=True)) # Populate the app registry with a stub for each application. app_labels = {model_state.app_label for model_state in models.values()} app_configs = [AppConfigStub(label) for label in sorted(real_apps + list(app_labels))] super(StateApps, self).__init__(app_configs) self.render_multiple(list(models.values()) + self.real_models) # If there are some lookups left, see if we can first resolve them # ourselves - sometimes fields are added after class_prepared is sent for lookup_model, operations in self._pending_lookups.items(): try: model = self.get_model(lookup_model[0], lookup_model[1]) except LookupError: app_label = "%s.%s" % (lookup_model[0], lookup_model[1]) if app_label == settings.AUTH_USER_MODEL and ignore_swappable: continue # Raise an error with a best-effort helpful message # (only for the first issue). Error message should look like: # "ValueError: Lookup failed for model referenced by # field migrations.Book.author: migrations.Author" msg = "Lookup failed for model referenced by field {field}: {model[0]}.{model[1]}" raise ValueError(msg.format(field=operations[0][1], model=lookup_model)) else: do_pending_lookups(model)
def __init__(self, real_apps, models, ignore_swappable=False): # Any apps in self.real_apps should have all their models included # in the render. We don't use the original model instances as there # are some variables that refer to the Apps object. # FKs/M2Ms from real apps are also not included as they just # mess things up with partial states (due to lack of dependencies) self.real_models = [] for app_label in real_apps: app = global_apps.get_app_config(app_label) for model in app.get_models(): self.real_models.append( ModelState.from_model(model, exclude_rels=True)) # Populate the app registry with a stub for each application. app_labels = {model_state.app_label for model_state in models.values()} app_configs = [ AppConfigStub(label) for label in sorted(real_apps + list(app_labels)) ] super().__init__(app_configs) # The lock gets in the way of copying as implemented in clone(), which # is called whenever Django duplicates a StateApps before updating it. self._lock = None self.render_multiple(list(models.values()) + self.real_models) # There shouldn't be any operations pending at this point. from django.core.checks.model_checks import _check_lazy_references ignore = {make_model_tuple(settings.AUTH_USER_MODEL) } if ignore_swappable else set() errors = _check_lazy_references(self, ignore=ignore) if errors: raise ValueError("\n".join(error.msg for error in errors))
def __init__(self, real_apps, models, ignore_swappable=False): # Any apps in self.real_apps should have all their models included # in the render. We don't use the original model instances as there # are some variables that refer to the Apps object. # FKs/M2Ms from real apps are also not included as they just # mess things up with partial states (due to lack of dependencies) self.real_models = [] for app_label in real_apps: app = global_apps.get_app_config(app_label) for model in app.get_models(): self.real_models.append(ModelState.from_model(model, exclude_rels=True)) # Populate the app registry with a stub for each application. app_labels = {model_state.app_label for model_state in models.values()} app_configs = [AppConfigStub(label) for label in sorted(real_apps + list(app_labels))] super(StateApps, self).__init__(app_configs) self.render_multiple(list(models.values()) + self.real_models) # There shouldn't be any operations pending at this point. pending_models = set(self._pending_operations) if ignore_swappable: pending_models -= {make_model_tuple(settings.AUTH_USER_MODEL)} if pending_models: msg = "Unhandled pending operations for models: %s" labels = (".".join(model_key) for model_key in self._pending_operations) raise ValueError(msg % ", ".join(labels))
def get_all_models(app_label=None): """Returns all model classes of all apps, including registered abstract ones. The resulting data structure is a dictionary which maps the class names to the model classes. Note that every app must have a ``models.py`` module. This ``models.py`` may be empty, though. :param app_label: the name of the app whose models should be returned :type app_label: unicode :return: all models of all apps :rtype: dict mapping str to ``class`` """ global all_models, abstract_models if app_label: result = dict((model.__name__, model) for model in apps.get_app_config(app_label).get_models()) result.update((model.__name__, model) for model in abstract_models if model._meta.app_label == app_label) return result if all_models is None: abstract_models = frozenset(abstract_models) all_models = dict((model.__name__, model) for model in apps.get_models()) all_models.update((model.__name__, model) for model in abstract_models) return all_models.copy()
def __init__(self, real_apps, models, ignore_swappable=False): # Any apps in self.real_apps should have all their models included # in the render. We don't use the original model instances as there # are some variables that refer to the Apps object. # FKs/M2Ms from real apps are also not included as they just # mess things up with partial states (due to lack of dependencies) self.real_models = [] for app_label in real_apps: app = global_apps.get_app_config(app_label) for model in app.get_models(): self.real_models.append(ModelState.from_model(model, exclude_rels=True)) # Populate the app registry with a stub for each application. app_labels = {model_state.app_label for model_state in models.values()} app_configs = [AppConfigStub(label) for label in sorted(real_apps + list(app_labels))] super(StateApps, self).__init__(app_configs) # The lock gets in the way of copying as implemented in clone(), which # is called whenever Django duplicates a StateApps before updating it. self._lock = None self.render_multiple(list(models.values()) + self.real_models) # There shouldn't be any operations pending at this point. from django.core.checks.model_checks import _check_lazy_references ignore = {make_model_tuple(settings.AUTH_USER_MODEL)} if ignore_swappable else set() errors = _check_lazy_references(self, ignore=ignore) if errors: raise ValueError("\n".join(error.msg for error in errors))
def render(self, include_real=None, ignore_swappable=False, skip_cache=False): "Turns the project state into actual models in a new Apps" if self.apps is None or skip_cache: # Any apps in self.real_apps should have all their models included # in the render. We don't use the original model instances as there # are some variables that refer to the Apps object. # FKs/M2Ms from real apps are also not included as they just # mess things up with partial states (due to lack of dependencies) real_models = [] for app_label in self.real_apps: app = global_apps.get_app_config(app_label) for model in app.get_models(): real_models.append(ModelState.from_model(model, exclude_rels=True)) # Populate the app registry with a stub for each application. app_labels = set(model_state.app_label for model_state in self.models.values()) self.apps = Apps([AppConfigStub(label) for label in sorted(self.real_apps + list(app_labels))]) # We keep trying to render the models in a loop, ignoring invalid # base errors, until the size of the unrendered models doesn't # decrease by at least one, meaning there's a base dependency loop/ # missing base. unrendered_models = list(self.models.values()) + real_models while unrendered_models: new_unrendered_models = [] for model in unrendered_models: try: model.render(self.apps) except InvalidBasesError: new_unrendered_models.append(model) if len(new_unrendered_models) == len(unrendered_models): raise InvalidBasesError( "Cannot resolve bases for %r\nThis can happen if you are inheriting models from an " "app with migrations (e.g. contrib.auth)\n in an app with no migrations; see " "https://docs.djangoproject.com/en/1.7/topics/migrations/#dependencies " "for more" % new_unrendered_models ) unrendered_models = new_unrendered_models # make sure apps has no dangling references if self.apps._pending_lookups: # There's some lookups left. See if we can first resolve them # ourselves - sometimes fields are added after class_prepared is sent for lookup_model, operations in self.apps._pending_lookups.items(): try: model = self.apps.get_model(lookup_model[0], lookup_model[1]) except LookupError: app_label = "%s.%s" % (lookup_model[0], lookup_model[1]) if app_label == settings.AUTH_USER_MODEL and ignore_swappable: continue # Raise an error with a best-effort helpful message # (only for the first issue). Error message should look like: # "ValueError: Lookup failed for model referenced by # field migrations.Book.author: migrations.Author" msg = "Lookup failed for model referenced by field {field}: {model[0]}.{model[1]}" raise ValueError(msg.format(field=operations[0][1], model=lookup_model)) else: do_pending_lookups(model) try: return self.apps finally: if skip_cache: self.apps = None
def get(name, default=None): """Fetch this name from django's cache :param name: A name like app__ModelName such that name.split('__') will give you an app label and a model name suitable for get_model """ from django.apps import apps try: app_label, model_name = name.split(DJANGO_ENV_SPLIT) except ValueError: raise ValueError( "DataSet class name %r must be a `%s' separated combination " "of app label " "and model name. Alternatively, you can set " "Meta.django_app_label " "to match the DataSet class name to a model for that app." % ( name, DJANGO_ENV_SPLIT)) else: try: model = apps.get_app_config(app_label).get_model(model_name) except LookupError: return None else: return model
def lista_prodavnica(request): title = apps.get_app_config('prodavnice').verbose_name prodavnice = Prodavnica.objects.all() return render(request, "lista_prodavnica.html", { "title": title, "prodavnice": prodavnice })
def lista_artikala(request): title = apps.get_app_config('prodavnice').verbose_name artikli = Artikal.objects.all() return render(request, "lista_artikala.html", { "title": title, "artikli": artikli })
def get_models(app_mod=None, include_auto_created=False): """Return the models belonging to an app. Args: app_mod (module, optional): The application module. include_auto_created (bool, optional): Whether to return auto-created models (such as many-to-many models) in the results. Returns: list: The list of modules belonging to the app. """ if apps: # Django >= 1.7 if app_mod is None: return apps.get_models(include_auto_created=include_auto_created) else: app_label = app_mod.__name__.split('.')[-2] try: app_config = apps.get_app_config(app_label) return list(app_config.get_models( include_auto_created=include_auto_created)) except LookupError: return [] else: # Django < 1.7 return _get_models(app_mod, include_auto_created=include_auto_created)
def render(self, include_real=None): "Turns the project state into actual models in a new Apps" if self.apps is None: # Any apps in self.real_apps should have all their models included # in the render. We don't use the original model instances as there # are some variables that refer to the Apps object. real_models = [] for app_label in self.real_apps: app = global_apps.get_app_config(app_label) for model in app.get_models(): real_models.append(ModelState.from_model(model)) # Populate the app registry with a stub for each application. app_labels = set(model_state.app_label for model_state in self.models.values()) self.apps = Apps([AppConfigStub(label) for label in sorted(self.real_apps + list(app_labels))]) # We keep trying to render the models in a loop, ignoring invalid # base errors, until the size of the unrendered models doesn't # decrease by at least one, meaning there's a base dependency loop/ # missing base. unrendered_models = list(self.models.values()) + real_models while unrendered_models: new_unrendered_models = [] for model in unrendered_models: try: model.render(self.apps) except InvalidBasesError: new_unrendered_models.append(model) if len(new_unrendered_models) == len(unrendered_models): raise InvalidBasesError("Cannot resolve bases for %r" % new_unrendered_models) unrendered_models = new_unrendered_models # make sure apps has no dangling references if self.apps._pending_lookups: # There's some lookups left. See if we can first resolve them # ourselves - sometimes fields are added after class_prepared is sent for lookup_model, operations in self.apps._pending_lookups.items(): try: model = self.apps.get_model(lookup_model[0], lookup_model[1]) except LookupError: # If the lookup failed to something that looks like AUTH_USER_MODEL, # give a better error message about how you can't change it (#22563) extra_message = "" if "%s.%s" % (lookup_model[0], lookup_model[1]) == settings.AUTH_USER_MODEL: extra_message = ( "\nThe missing model matches AUTH_USER_MODEL; if you've changed the value of this" + "\nsetting after making a migration, be aware that this is not supported. If you" + "\nchange AUTH_USER_MODEL you must delete and recreate migrations for its app." ) # Raise an error with a best-effort helpful message # (only for the first issue). Error message should look like: # "ValueError: Lookup failed for model referenced by # field migrations.Book.author: migrations.Author" raise ValueError("Lookup failed for model referenced by field {field}: {model[0]}.{model[1]}{extra_message}".format( field = operations[0][1], model = lookup_model, extra_message = extra_message, )) else: do_pending_lookups(model) return self.apps
def get_source_model(): """ Returns project order model :return: order model :rtype: django.db.models.Model """ model_name = settings.ROSEVROBANK_SOURCE_MODEL app_label, model_name = model_name.split('.') model = apps.get_app_config(app_label).get_model(model_name) return model
def get_app(app_label, emptyOK=False): """Return the app with the given label. This returns the app from the app registry on Django >= 1.7, and from the old-style cache on Django < 1.7. The ``emptyOK`` argument is ignored for Django >= 1.7. Args: app_label (str): The label for the app containing the models. emptyOK (bool, optional): Impacts the return value if the app has no models in it. Returns: module: The app module, if available. If not available, and ``emptyOK`` is set, this will return ``None``. If ``emptyOK`` is not set, it will raise :py:exc:`~django.core.exceptions.ImproperlyConfigured`. Raises: django.core.exceptions.ImproperlyConfigured: The app module was not found, and ``emptyOK`` was ``False``. """ if apps: # Django >= 1.7 try: models_module = apps.get_app_config(app_label).models_module except LookupError as e: # Convert this to an ImproperlyConfigured. raise ImproperlyConfigured(*e.args) if models_module is None: if emptyOK: raise LookupError('..') raise ImproperlyConfigured( 'App with label %s is missing a models.py module.' % app_label) return models_module else: # Django < 1.7 return cache.get_app(app_label, emptyOK)
def get_app(app_label, emptyOK=False): """Return the app with the given label. This returns the app from the app registry on Django >= 1.7, and from the old-style cache on Django < 1.7. app_label (str): The label for the app containing the models. emptyOK (bool, optional): Impacts the return value if the app has no models in it. Returns: module: The app module, if available. If the app module is available, but the models module is not and ``emptyOK`` is set, this will return ``None``. Otherwise, if modules are not available, this will raise :py:exc:`~django.core.exceptions.ImproperlyConfigured`. Raises: django.core.exceptions.ImproperlyConfigured: The app module was not found, or it was found but a models module was not and ``emptyOK`` was ``False``. """ if apps: # Django >= 1.7 try: models_module = apps.get_app_config(app_label).models_module except LookupError as e: # Convert this to an ImproperlyConfigured. raise ImproperlyConfigured(*e.args) if models_module is None and not emptyOK: # This is the exact error that Django 1.6 provided. raise ImproperlyConfigured( 'App with label %s is missing a models.py module.' % app_label) return models_module else: # Django < 1.7 return cache.get_app(app_label, emptyOK)
# -*- coding: utf-8 -*- from django.apps.registry import apps from django.contrib import admin for model in apps.get_app_config('臺灣言語資料庫').get_models(): admin.site.register(model)
def get_app_list(context, order=True): admin_site = get_admin_site(context) request = context['request'] app_dict = {} for model, model_admin in admin_site._registry.items(): app_label = model._meta.app_label try: has_module_perms = model_admin.has_module_permission(request) except AttributeError: has_module_perms = request.user.has_module_perms(app_label) # Fix Django < 1.8 issue 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=admin_site.name) except NoReverseMatch: pass if perms.get('add', False): try: model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=admin_site.name) except NoReverseMatch: pass if app_label in app_dict: app_dict[app_label]['models'].append(model_dict) else: try: name = apps.get_app_config(app_label).verbose_name except NameError: name = app_label.title() app_dict[app_label] = { 'name': name, 'app_label': app_label, 'app_url': reverse( 'admin:app_list', kwargs={'app_label': app_label}, current_app=admin_site.name, ), 'has_module_perms': has_module_perms, 'models': [model_dict], } # Sort the apps alphabetically. app_list = list(app_dict.values()) if order: 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
def setUp(self): self.before_count = ContentType.objects.count() ContentType.objects.create(app_label='contenttypes_tests', model='Fake') self.app_config = apps.get_app_config('contenttypes_tests')
def setUp(self): self.before_count = ContentType.objects.count() self.content_type = ContentType.objects.create(app_label="contenttypes_tests", model="Fake") self.app_config = apps.get_app_config("contenttypes_tests")
def tearDown(self): app_config = apps.get_app_config('contenttypes_tests') models.signals.post_migrate.disconnect(self.assertOperationsInjected, sender=app_config)
def setUp(self): app_config = apps.get_app_config("contenttypes_tests") models.signals.post_migrate.connect(self.assertOperationsInjected, sender=app_config)
def setUp(self): self.before_count = ContentType.objects.count() ContentType.objects.create(name='fake', app_label='contenttypes_tests', model='Fake') self.app_config = apps.get_app_config('contenttypes_tests') self.old_stdout = sys.stdout sys.stdout = StringIO()
from __future__ import unicode_literals