Python django.utils.module_loading.module_has_submodule() Examples

The following are 30 code examples of django.utils.module_loading.module_has_submodule(). 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.utils.module_loading , or try the search function .
Example #1
Source File: registry.py    From django-badgify with MIT License 6 votes vote down vote up
def _autodiscover(recipes):
    import copy
    from django.conf import settings

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

    from django.utils.module_loading import module_has_submodule

    for app in settings.INSTALLED_APPS:
        mod = import_module(app)
        try:
            before_import_recipes = copy.copy(recipes)
            import_module('%s.badgify_recipes' % app)
        except Exception:
            recipes = before_import_recipes
            if module_has_submodule(mod, 'badgify_recipes'):
                raise 
Example #2
Source File: resources_discoverer.py    From rotest with MIT License 6 votes vote down vote up
def get_resources():
    """Get all the resource classes from apps declared in settings.py.

    Returns:
        dict. all resource classes found in the application {name: class}.
    """
    declared_apps = settings.INSTALLED_APPS
    resources = {}

    for app_name in declared_apps:
        app_module = import_module(app_name)

        if module_has_submodule(app_module, RESOURCES_MODULE_NAME):
            resources_module = '%s.%s' % (app_name, RESOURCES_MODULE_NAME)
            app_resources = _import_resources_from_module(resources_module)
            resources.update(app_resources)

    return resources 
Example #3
Source File: simple.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def get_tests(app_module):
    parts = app_module.__name__.split('.')
    prefix, last = parts[:-1], parts[-1]
    try:
        test_module = import_module('.'.join(prefix + [TEST_MODULE]))
    except ImportError:
        # Couldn't import tests.py. Was it due to a missing file, or
        # due to an import error in a tests.py that actually exists?
        # app_module either points to a models.py file, or models/__init__.py
        # Tests are therefore either in same directory, or one level up
        if last == 'models':
            app_root = import_module('.'.join(prefix))
        else:
            app_root = app_module

        if not module_has_submodule(app_root, TEST_MODULE):
            test_module = None
        else:
            # The module exists, so there must be an import error in the test
            # module itself.
            raise
    return test_module 
Example #4
Source File: simple.py    From anytask with MIT License 6 votes vote down vote up
def get_tests(app_module):
    parts = app_module.__name__.split('.')
    prefix, last = parts[:-1], parts[-1]
    try:
        test_module = import_module('.'.join(prefix + [TEST_MODULE]))
    except ImportError:
        # Couldn't import tests.py. Was it due to a missing file, or
        # due to an import error in a tests.py that actually exists?
        # app_module either points to a models.py file, or models/__init__.py
        # Tests are therefore either in same directory, or one level up
        if last == 'models':
            app_root = import_module('.'.join(prefix))
        else:
            app_root = app_module

        if not module_has_submodule(app_root, TEST_MODULE):
            test_module = None
        else:
            # The module exists, so there must be an import error in the test
            # module itself.
            raise
    return test_module 
Example #5
Source File: config.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def import_models(self, all_models):
        # Dictionary of models for this app, primarily maintained in the
        # 'all_models' attribute of the Apps this AppConfig is attached to.
        # Injected as a parameter because it gets populated when models are
        # imported, which might happen before populate() imports models.
        self.models = all_models

        if module_has_submodule(self.module, MODELS_MODULE_NAME):
            models_module_name = '%s.%s' % (self.name, MODELS_MODULE_NAME)
            self.models_module = import_module(models_module_name) 
Example #6
Source File: load_dev_data.py    From steemprojects.com with MIT License 5 votes vote down vote up
def handle(self, *args, **options): 
        print("Commencing dev data import", file=stdout)

        for app in settings.INSTALLED_APPS:
            mod = import_module(app)
            # Attempt to import the app's test.data module.
            try:
                mod_data = import_module('%s.tests.data' % app)
                mod_data.load()
            except:
                # Decide whether to bubble up this error. If the app just
                # doesn't have an test.data module, we can ignore the error
                # attempting to import it, otherwise we want it to bubble up.
                if module_has_submodule(mod, 'test.data'):
                    raise 
Example #7
Source File: hooks.py    From allianceauth with GNU General Public License v2.0 5 votes vote down vote up
def get_app_submodules(module_name):
    """
    Get a specific sub module of the app
    :param module_name: module name to get
    :return: name, module tuple
    """
    for name, module in get_app_modules():
        if module_has_submodule(module, module_name):
            yield name, import_module('{0}.{1}'.format(name, module_name)) 
Example #8
Source File: urlresolvers.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def get_callable(lookup_view, can_fail=False):
    """
    Convert a string version of a function name to the callable object.

    If the lookup_view is not an import path, it is assumed to be a URL pattern
    label and the original string is returned.

    If can_fail is True, lookup_view might be a URL pattern label, so errors
    during the import fail and the string is returned.
    """
    if not callable(lookup_view):
        mod_name, func_name = get_mod_func(lookup_view)
        if func_name == '':
            return lookup_view

        try:
            mod = import_module(mod_name)
        except ImportError:
            parentmod, submod = get_mod_func(mod_name)
            if (not can_fail and submod != '' and
                    not module_has_submodule(import_module(parentmod), submod)):
                raise ViewDoesNotExist(
                    "Could not import %s. Parent module %s does not exist." %
                    (lookup_view, mod_name))
            if not can_fail:
                raise
        else:
            try:
                lookup_view = getattr(mod, func_name)
                if not callable(lookup_view):
                    raise ViewDoesNotExist(
                        "Could not import %s.%s. View is not callable." %
                        (mod_name, func_name))
            except AttributeError:
                if not can_fail:
                    raise ViewDoesNotExist(
                        "Could not import %s. View does not exist in module %s." %
                        (lookup_view, mod_name))
    return lookup_view 
Example #9
Source File: base.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def is_library_missing(name):
    """Check if library that failed to load cannot be found under any
    templatetags directory or does exist but fails to import.

    Non-existing condition is checked recursively for each subpackage in cases
    like <appdir>/templatetags/subpackage/package/module.py.
    """
    # Don't bother to check if '.' is in name since any name will be prefixed
    # with some template root.
    path, module = name.rsplit('.', 1)
    try:
        package = import_module(path)
        return not module_has_submodule(package, module)
    except ImportError:
        return is_library_missing(path) 
Example #10
Source File: base.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def is_library_missing(name):
    """Check if library that failed to load cannot be found under any
    templatetags directory or does exist but fails to import.

    Non-existing condition is checked recursively for each subpackage in cases
    like <appdir>/templatetags/subpackage/package/module.py.
    """
    # Don't bother to check if '.' is in name since any name will be prefixed
    # with some template root.
    path, module = name.rsplit('.', 1)
    try:
        package = import_module(path)
        return not module_has_submodule(package, module)
    except ImportError:
        return is_library_missing(path) 
Example #11
Source File: loading.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def load_app(self, app_name, can_postpone=False):
        """
        Loads the app with the provided fully qualified name, and returns the
        model module.
        """
        self.handled[app_name] = None
        self.nesting_level += 1
        app_module = import_module(app_name)
        try:
            models = import_module('.models', app_name)
        except ImportError:
            self.nesting_level -= 1
            # If the app doesn't have a models module, we can just ignore the
            # ImportError and return no models for it.
            if not module_has_submodule(app_module, 'models'):
                return None
            # But if the app does have a models module, we need to figure out
            # whether to suppress or propagate the error. If can_postpone is
            # True then it may be that the package is still being imported by
            # Python and the models module isn't available yet. So we add the
            # app to the postponed list and we'll try it again after all the
            # recursion has finished (in populate). If can_postpone is False
            # then it's time to raise the ImportError.
            else:
                if can_postpone:
                    self.postponed.append(app_name)
                    return None
                else:
                    raise

        self.nesting_level -= 1
        if models not in self.app_store:
            self.app_store[models] = len(self.app_store)
            self.app_labels[self._label_for(models)] = models
        return models 
Example #12
Source File: utils.py    From django-hyper-editor with MIT License 5 votes vote down vote up
def load_hyper_blocks():
    submodule_name = 'hyper_blocks'
    for name, module in get_app_modules():
        if module_has_submodule(module, submodule_name):
            yield name, import_module('%s.%s' % (name, submodule_name)) 
Example #13
Source File: apps.py    From wagtailstreamforms with MIT License 5 votes vote down vote up
def get_app_submodules(submodule_name):
    """
    Searches each app module for the specified submodule
    yields tuples of (app_name, module)
    """

    for name, module in get_app_modules():
        if module_has_submodule(module, submodule_name):
            yield name, import_module("%s.%s" % (name, submodule_name)) 
Example #14
Source File: apps.py    From zentral with Apache License 2.0 5 votes vote down vote up
def import_probes(self):
        if module_has_submodule(self.module, PROBES_MODULE_NAME):
            probes_module_name = "%s.%s" % (self.name, PROBES_MODULE_NAME)
            self.probes_module = import_module(probes_module_name)
            logger.debug('Probes module "%s" imported', probes_module_name) 
Example #15
Source File: apps.py    From zentral with Apache License 2.0 5 votes vote down vote up
def import_events(self):
        if module_has_submodule(self.module, EVENTS_MODULE_NAME):
            events_module_name = "%s.%s" % (self.name, EVENTS_MODULE_NAME)
            self.events_module = import_module(events_module_name)
            logger.debug('Events module "%s" loaded', events_module_name)
            events_templates_dir = os.path.join(self.path, 'events/templates')
            if os.path.exists(events_templates_dir):
                self.events_templates_dir = events_templates_dir
                logger.debug('Found events templates dir "%s"', events_templates_dir) 
Example #16
Source File: registry.py    From django-versatileimagefield with MIT License 5 votes vote down vote up
def autodiscover():
    """
    Discover versatileimagefield.py modules.

    Iterate over django.apps.get_app_configs() and discover
    versatileimagefield.py modules.
    """
    from importlib import import_module
    from django.apps import apps
    from django.utils.module_loading import module_has_submodule

    for app_config in apps.get_app_configs():
        # Attempt to import the app's module.

        try:
            before_import_sizedimage_registry = copy.copy(
                versatileimagefield_registry._sizedimage_registry
            )
            before_import_filter_registry = copy.copy(
                versatileimagefield_registry._filter_registry
            )
            import_module('%s.versatileimagefield' % app_config.name)
        except Exception:
            # Reset the versatileimagefield_registry to the state before the
            # last import as this import will have to reoccur on the next
            # request and this could raise NotRegistered and AlreadyRegistered
            # exceptions (see django ticket #8245).
            versatileimagefield_registry._sizedimage_registry = \
                before_import_sizedimage_registry
            versatileimagefield_registry._filter_registry = \
                before_import_filter_registry

            # Decide whether to bubble up this error. If the app just
            # doesn't have the module in question, we can ignore the error
            # attempting to import it, otherwise we want it to bubble up.
            if module_has_submodule(app_config.module, 'versatileimagefield'):
                raise 
Example #17
Source File: base.py    From django-leonardo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_app_modules(self, apps):
        """return array of imported leonardo modules for apps
        """
        modules = getattr(self, "_modules", [])

        if not modules:
            from django.utils.module_loading import module_has_submodule

            # Try importing a modules from the module package
            package_string = '.'.join(['leonardo', 'module'])

            for app in apps:
                exc = '...'
                try:
                    # check if is not full app
                    _app = import_module(app)
                except Exception as e:
                    _app = False
                    exc = e

                if module_has_submodule(
                        import_module(package_string), app) or _app:
                    if _app:
                        mod = _app
                    else:
                        mod = import_module('.{0}'.format(app), package_string)
                    if mod:
                        modules.append(mod)
                        continue

                warnings.warn('%s was skipped because %s ' % (app, exc))

            self._modules = modules
        return self._modules 
Example #18
Source File: apps.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_app_submodules(submodule_name):
    """
    Searches each app module for the specified submodule
    yields tuples of (app_name, module)
    """
    for name, module in get_app_modules():
        if module_has_submodule(module, submodule_name):
            yield name, import_module('%s.%s' % (name, submodule_name)) 
Example #19
Source File: discover.py    From rele with Apache License 2.0 5 votes vote down vote up
def discover_subs_modules():
    logger.debug("Autodiscovering subs...")
    app_configs = apps.get_app_configs()
    subs_modules = []
    for conf in app_configs:
        if module_has_submodule(conf.module, "subs"):
            module = conf.name + ".subs"
            subs_modules.append(module)
            logger.debug(" * Discovered subs module: %r" % module)
    return subs_modules 
Example #20
Source File: test_fixtures.py    From zulip with Apache License 2.0 5 votes vote down vote up
def get_migration_status(**options: Any) -> str:
    verbosity = options.get('verbosity', 1)

    for app_config in apps.get_app_configs():
        if module_has_submodule(app_config.module, "management"):
            import_module('.management', app_config.name)

    app_label = options['app_label'] if options.get('app_label') else None
    db = options.get('database', DEFAULT_DB_ALIAS)
    out = StringIO()
    command_args = ['--list']
    if app_label:
        command_args.append(app_label)

    call_command(
        'showmigrations',
        *command_args,
        database=db,
        no_color=options.get('no_color', False),
        settings=options.get('settings', os.environ['DJANGO_SETTINGS_MODULE']),
        stdout=out,
        traceback=options.get('traceback', True),
        verbosity=verbosity,
    )
    connections.close_all()
    out.seek(0)
    output = out.read()
    return re.sub(r'\x1b\[(1|0)m', '', output) 
Example #21
Source File: test_module_loading.py    From django-compat with MIT License 5 votes vote down vote up
def test_loader(self):
        "Normal module existence can be tested"
        test_module = import_module('compat.tests.utils_tests.test_module')
        test_no_submodule = import_module(
            'compat.tests.utils_tests.test_no_submodule')

        # An importable child
        self.assertTrue(module_has_submodule(test_module, 'good_module'))
        mod = import_module('compat.tests.utils_tests.test_module.good_module')
        self.assertEqual(mod.content, 'Good Module')

        # A child that exists, but will generate an import error if loaded
        self.assertTrue(module_has_submodule(test_module, 'bad_module'))
        with self.assertRaises(ImportError):
            import_module('compat.tests.utils_tests.test_module.bad_module')

        # A child that doesn't exist
        self.assertFalse(module_has_submodule(test_module, 'no_such_module'))
        with self.assertRaises(ImportError):
            import_module('compat.tests.utils_tests.test_module.no_such_module')

        # A child that doesn't exist, but is the name of a package on the path
        self.assertFalse(module_has_submodule(test_module, 'django'))
        with self.assertRaises(ImportError):
            import_module('compat.tests.utils_tests.test_module.django')

        # Don't be confused by caching of import misses
        import types  # NOQA: causes attempted import of utils_tests.types
        self.assertFalse(module_has_submodule(sys.modules['compat.tests.utils_tests'], 'types'))

        # A module which doesn't have a __path__ (so no submodules)
        self.assertFalse(module_has_submodule(test_no_submodule, 'anything'))
        with self.assertRaises(ImportError):
            import_module('compat.tests.utils_tests.test_no_submodule.anything') 
Example #22
Source File: __init__.py    From StormOnline with Apache License 2.0 4 votes vote down vote up
def autodiscover():
    """
    Auto-discover INSTALLED_APPS admin.py modules and fail silently when
    not present. This forces an import on them to register any admin bits they
    may want.
    """

    from importlib import import_module
    from django.conf import settings
    from django.utils.module_loading import module_has_submodule
    from django.apps import apps

    setattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap3')
    setattr(settings, 'CRISPY_CLASS_CONVERTERS', {
        "textinput": "textinput textInput form-control",
        "fileinput": "fileinput fileUpload form-control",
        "passwordinput": "textinput textInput form-control",
    })

    from xadmin.views import register_builtin_views
    register_builtin_views(site)

    # load xadmin settings from XADMIN_CONF module
    try:
        xadmin_conf = getattr(settings, 'XADMIN_CONF', 'xadmin_conf.py')
        conf_mod = import_module(xadmin_conf)
    except Exception:
        conf_mod = None

    if conf_mod:
        for key in dir(conf_mod):
            setting = getattr(conf_mod, key)
            try:
                if issubclass(setting, Settings):
                    site.register_settings(setting.__name__, setting)
            except Exception:
                pass

    from xadmin.plugins import register_builtin_plugins
    register_builtin_plugins(site)

    for app_config in apps.get_app_configs():
        mod = import_module(app_config.name)
        # Attempt to import the app's admin module.
        try:
            before_import_registry = site.copy_registry()
            import_module('%s.adminx' % app_config.name)
        except:
            # Reset the model registry to the state before the last import as
            # this import will have to reoccur on the next request and this
            # could raise NotRegistered and AlreadyRegistered exceptions
            # (see #8245).
            site.restore_registry(before_import_registry)

            # Decide whether to bubble up this error. If the app just
            # doesn't have an admin module, we can ignore the error
            # attempting to import it, otherwise we want it to bubble up.
            if module_has_submodule(mod, 'adminx'):
                raise 
Example #23
Source File: urlresolvers.py    From GTDWeb with GNU General Public License v2.0 4 votes vote down vote up
def get_callable(lookup_view, can_fail=False):
    """
    Return a callable corresponding to lookup_view. This function is used
    by both resolve() and reverse(), so can_fail allows the caller to choose
    between returning the input as is and raising an exception when the input
    string can't be interpreted as an import path.

    If lookup_view is already a callable, return it.
    If lookup_view is a string import path that can be resolved to a callable,
      import that callable and return it.
    If lookup_view is some other kind of string and can_fail is True, the string
      is returned as is. If can_fail is False, an exception is raised (either
      ImportError or ViewDoesNotExist).
    """
    if callable(lookup_view):
        return lookup_view

    mod_name, func_name = get_mod_func(lookup_view)
    if not func_name:  # No '.' in lookup_view
        if can_fail:
            return lookup_view
        else:
            raise ImportError(
                "Could not import '%s'. The path must be fully qualified." %
                lookup_view)

    try:
        mod = import_module(mod_name)
    except ImportError:
        if can_fail:
            return lookup_view
        else:
            parentmod, submod = get_mod_func(mod_name)
            if submod and not module_has_submodule(import_module(parentmod), submod):
                raise ViewDoesNotExist(
                    "Could not import '%s'. Parent module %s does not exist." %
                    (lookup_view, mod_name))
            else:
                raise
    else:
        try:
            view_func = getattr(mod, func_name)
        except AttributeError:
            if can_fail:
                return lookup_view
            else:
                raise ViewDoesNotExist(
                    "Could not import '%s'. View does not exist in module %s." %
                    (lookup_view, mod_name))
        else:
            if not callable(view_func):
                # For backwards compatibility this is raised regardless of can_fail
                raise ViewDoesNotExist(
                    "Could not import '%s.%s'. View is not callable." %
                    (mod_name, func_name))

            return view_func 
Example #24
Source File: utils.py    From bioforum with MIT License 4 votes vote down vote up
def get_callable(lookup_view):
    """
    Return a callable corresponding to lookup_view.
    * If lookup_view is already a callable, return it.
    * If lookup_view is a string import path that can be resolved to a callable,
      import that callable and return it, otherwise raise an exception
      (ImportError or ViewDoesNotExist).
    """
    if callable(lookup_view):
        return lookup_view

    if not isinstance(lookup_view, str):
        raise ViewDoesNotExist("'%s' is not a callable or a dot-notation path" % lookup_view)

    mod_name, func_name = get_mod_func(lookup_view)
    if not func_name:  # No '.' in lookup_view
        raise ImportError("Could not import '%s'. The path must be fully qualified." % lookup_view)

    try:
        mod = import_module(mod_name)
    except ImportError:
        parentmod, submod = get_mod_func(mod_name)
        if submod and not module_has_submodule(import_module(parentmod), submod):
            raise ViewDoesNotExist(
                "Could not import '%s'. Parent module %s does not exist." %
                (lookup_view, mod_name)
            )
        else:
            raise
    else:
        try:
            view_func = getattr(mod, func_name)
        except AttributeError:
            raise ViewDoesNotExist(
                "Could not import '%s'. View does not exist in module %s." %
                (lookup_view, mod_name)
            )
        else:
            if not callable(view_func):
                raise ViewDoesNotExist(
                    "Could not import '%s.%s'. View is not callable." %
                    (mod_name, func_name)
                )
            return view_func 
Example #25
Source File: __init__.py    From ImitationTmall_Django with GNU General Public License v3.0 4 votes vote down vote up
def autodiscover():
    """
    Auto-discover INSTALLED_APPS admin.py modules and fail silently when
    not present. This forces an import on them to register any admin bits they
    may want.
    """

    from importlib import import_module
    from django.conf import settings
    from django.utils.module_loading import module_has_submodule
    setattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap3')
    setattr(settings, 'CRISPY_CLASS_CONVERTERS', {
        "textinput": "textinput textInput form-control",
        "fileinput": "fileinput fileUpload form-control",
        "passwordinput": "textinput textInput form-control",
    })

    from xadmin.views import register_builtin_views
    register_builtin_views(site)

    # load xadmin settings from XADMIN_CONF module
    try:
        xadmin_conf = getattr(settings, 'XADMIN_CONF', 'xadmin_conf.py')
        conf_mod = import_module(xadmin_conf)
    except Exception:
        conf_mod = None

    if conf_mod:
        for key in dir(conf_mod):
            setting = getattr(conf_mod, key)
            try:
                if issubclass(setting, Settings):
                    site.register_settings(setting.__name__, setting)
            except Exception:
                pass

    from xadmin.plugins import register_builtin_plugins
    register_builtin_plugins(site)

    for app in settings.INSTALLED_APPS:
        mod = import_module(app)
        # Attempt to import the app's admin module.
        try:
            before_import_registry = site.copy_registry()
            import_module('%s.adminx' % app)
        except:
            # Reset the model registry to the state before the last import as
            # this import will have to reoccur on the next request and this
            # could raise NotRegistered and AlreadyRegistered exceptions
            # (see #8245).
            site.restore_registry(before_import_registry)

            # Decide whether to bubble up this error. If the app just
            # doesn't have an admin module, we can ignore the error
            # attempting to import it, otherwise we want it to bubble up.
            if module_has_submodule(mod, 'adminx'):
                raise 
Example #26
Source File: __init__.py    From Dailyfresh-B2C with Apache License 2.0 4 votes vote down vote up
def autodiscover():
    """
    Auto-discover INSTALLED_APPS admin.py modules and fail silently when
    not present. This forces an import on them to register any admin bits they
    may want.
    """

    from importlib import import_module
    from django.conf import settings
    from django.utils.module_loading import module_has_submodule
    from django.apps import apps

    setattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap3')
    setattr(settings, 'CRISPY_CLASS_CONVERTERS', {
        "textinput": "textinput textInput form-control",
        "fileinput": "fileinput fileUpload form-control",
        "passwordinput": "textinput textInput form-control",
    })

    from xadmin.views import register_builtin_views
    register_builtin_views(site)

    # load xadmin settings from XADMIN_CONF module
    try:
        xadmin_conf = getattr(settings, 'XADMIN_CONF', 'xadmin_conf.py')
        conf_mod = import_module(xadmin_conf)
    except Exception:
        conf_mod = None

    if conf_mod:
        for key in dir(conf_mod):
            setting = getattr(conf_mod, key)
            try:
                if issubclass(setting, Settings):
                    site.register_settings(setting.__name__, setting)
            except Exception:
                pass

    from xadmin.plugins import register_builtin_plugins
    register_builtin_plugins(site)

    for app_config in apps.get_app_configs():
        mod = import_module(app_config.name)
        # Attempt to import the app's admin module.
        try:
            before_import_registry = site.copy_registry()
            import_module('%s.adminx' % app_config.name)
        except:
            # Reset the model registry to the state before the last import as
            # this import will have to reoccur on the next request and this
            # could raise NotRegistered and AlreadyRegistered exceptions
            # (see #8245).
            site.restore_registry(before_import_registry)

            # Decide whether to bubble up this error. If the app just
            # doesn't have an admin module, we can ignore the error
            # attempting to import it, otherwise we want it to bubble up.
            if module_has_submodule(mod, 'adminx'):
                raise 
Example #27
Source File: __init__.py    From online with GNU Affero General Public License v3.0 4 votes vote down vote up
def autodiscover():
    """
    Auto-discover INSTALLED_APPS admin.py modules and fail silently when
    not present. This forces an import on them to register any admin bits they
    may want.
    """

    from importlib import import_module
    from django.conf import settings
    from django.utils.module_loading import module_has_submodule
    from django.apps import apps

    setattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap3')
    setattr(settings, 'CRISPY_CLASS_CONVERTERS', {
        "textinput": "textinput textInput form-control",
        "fileinput": "fileinput fileUpload form-control",
        "passwordinput": "textinput textInput form-control",
    })

    from xadmin.views import register_builtin_views
    register_builtin_views(site)

    # load xadmin settings from XADMIN_CONF module
    try:
        xadmin_conf = getattr(settings, 'XADMIN_CONF', 'xadmin_conf.py')
        conf_mod = import_module(xadmin_conf)
    except Exception:
        conf_mod = None

    if conf_mod:
        for key in dir(conf_mod):
            setting = getattr(conf_mod, key)
            try:
                if issubclass(setting, Settings):
                    site.register_settings(setting.__name__, setting)
            except Exception:
                pass

    from xadmin.plugins import register_builtin_plugins
    register_builtin_plugins(site)

    for app_config in apps.get_app_configs():
        mod = import_module(app_config.name)
        # Attempt to import the app's admin module.
        try:
            before_import_registry = site.copy_registry()
            import_module('%s.adminx' % app_config.name)
        except:
            # Reset the model registry to the state before the last import as
            # this import will have to reoccur on the next request and this
            # could raise NotRegistered and AlreadyRegistered exceptions
            # (see #8245).
            site.restore_registry(before_import_registry)

            # Decide whether to bubble up this error. If the app just
            # doesn't have an admin module, we can ignore the error
            # attempting to import it, otherwise we want it to bubble up.
            if module_has_submodule(mod, 'adminx'):
                raise 
Example #28
Source File: __init__.py    From devops with MIT License 4 votes vote down vote up
def autodiscover():
    """
    Auto-discover INSTALLED_APPS admin.py modules and fail silently when
    not present. This forces an import on them to register any admin bits they
    may want.
    """

    from django.conf import settings
    from django.utils.module_loading import module_has_submodule, import_module

    setattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap3')
    setattr(settings, 'CRISPY_CLASS_CONVERTERS', {
        "textinput": "textinput textInput form-control",
        "fileinput": "fileinput fileUpload form-control",
        "passwordinput": "textinput textInput form-control",
    })

    from xadmin.views import register_builtin_views
    register_builtin_views(site)

    # load xadmin settings from XADMIN_CONF module
    try:
        xadmin_conf = getattr(settings, 'XADMIN_CONF', 'xadmin_conf.py')
        conf_mod = import_module(xadmin_conf)
    except Exception:
        conf_mod = None

    if conf_mod:
        for key in dir(conf_mod):
            setting = getattr(conf_mod, key)
            try:
                if issubclass(setting, Settings):
                    site.register_settings(setting.__name__, setting)
            except Exception:
                pass

    from xadmin.plugins import register_builtin_plugins
    register_builtin_plugins(site)

    from django.apps import apps
    
    for app_config in apps.get_app_configs():
        # Attempt to import the app's admin module.
        try:
            before_import_registry = site.copy_registry()
            import_module('%s.adminx' % app_config.name)
        except:
            # Reset the model registry to the state before the last import as
            # this import will have to reoccur on the next request and this
            # could raise NotRegistered and AlreadyRegistered exceptions
            # (see #8245).
            site.restore_registry(before_import_registry)

            # Decide whether to bubble up this error. If the app just
            # doesn't have an admin module, we can ignore the error
            # attempting to import it, otherwise we want it to bubble up.
            if module_has_submodule(app_config.module, 'adminx'):
                raise 
Example #29
Source File: __init__.py    From imoocc with GNU General Public License v2.0 4 votes vote down vote up
def autodiscover():
    """
    Auto-discover INSTALLED_APPS admin.py modules and fail silently when
    not present. This forces an import on them to register any admin bits they
    may want.
    """

    from importlib import import_module
    from django.conf import settings
    from django.utils.module_loading import module_has_submodule
    from django.apps import apps

    setattr(settings, 'CRISPY_TEMPLATE_PACK', 'bootstrap3')
    setattr(settings, 'CRISPY_CLASS_CONVERTERS', {
        "textinput": "textinput textInput form-control",
        "fileinput": "fileinput fileUpload form-control",
        "passwordinput": "textinput textInput form-control",
    })

    from xadmin.views import register_builtin_views
    register_builtin_views(site)

    # load xadmin settings from XADMIN_CONF module
    try:
        xadmin_conf = getattr(settings, 'XADMIN_CONF', 'xadmin_conf.py')
        conf_mod = import_module(xadmin_conf)
    except Exception:
        conf_mod = None

    if conf_mod:
        for key in dir(conf_mod):
            setting = getattr(conf_mod, key)
            try:
                if issubclass(setting, Settings):
                    site.register_settings(setting.__name__, setting)
            except Exception:
                pass

    from xadmin.plugins import register_builtin_plugins
    register_builtin_plugins(site)

    for app_config in apps.get_app_configs():
        mod = import_module(app_config.name)
        # Attempt to import the app's admin module.
        try:
            before_import_registry = site.copy_registry()
            import_module('%s.adminx' % app_config.name)
        except:
            # Reset the model registry to the state before the last import as
            # this import will have to reoccur on the next request and this
            # could raise NotRegistered and AlreadyRegistered exceptions
            # (see #8245).
            site.restore_registry(before_import_registry)

            # Decide whether to bubble up this error. If the app just
            # doesn't have an admin module, we can ignore the error
            # attempting to import it, otherwise we want it to bubble up.
            if module_has_submodule(mod, 'adminx'):
                raise 
Example #30
Source File: utils.py    From python2017 with MIT License 4 votes vote down vote up
def get_callable(lookup_view):
    """
    Return a callable corresponding to lookup_view.
    * If lookup_view is already a callable, return it.
    * If lookup_view is a string import path that can be resolved to a callable,
      import that callable and return it, otherwise raise an exception
      (ImportError or ViewDoesNotExist).
    """
    if callable(lookup_view):
        return lookup_view

    if not isinstance(lookup_view, six.string_types):
        raise ViewDoesNotExist("'%s' is not a callable or a dot-notation path" % lookup_view)

    mod_name, func_name = get_mod_func(lookup_view)
    if not func_name:  # No '.' in lookup_view
        raise ImportError("Could not import '%s'. The path must be fully qualified." % lookup_view)

    try:
        mod = import_module(mod_name)
    except ImportError:
        parentmod, submod = get_mod_func(mod_name)
        if submod and not module_has_submodule(import_module(parentmod), submod):
            raise ViewDoesNotExist(
                "Could not import '%s'. Parent module %s does not exist." %
                (lookup_view, mod_name)
            )
        else:
            raise
    else:
        try:
            view_func = getattr(mod, func_name)
        except AttributeError:
            raise ViewDoesNotExist(
                "Could not import '%s'. View does not exist in module %s." %
                (lookup_view, mod_name)
            )
        else:
            if not callable(view_func):
                raise ViewDoesNotExist(
                    "Could not import '%s.%s'. View is not callable." %
                    (mod_name, func_name)
                )
            return view_func