Ticket #7922: autodiscover_getattr_import_option_2.diff

File autodiscover_getattr_import_option_2.diff, 1.3 KB (added by oyvind, 16 years ago)

Getattr import solution 2

  • django/contrib/admin/__init__.py

    diff --git a/django/contrib/admin/__init__.py b/django/contrib/admin/__init__.py
    index 56b64fa..b9ed1ff 100644
    a b  
     1from django.utils.importutils import getattr_import, module_or_none
    12from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
    23from django.contrib.admin.options import StackedInline, TabularInline
    34from django.contrib.admin.sites import AdminSite, site
    def autodiscover():  
    1011    """
    1112    from django.conf import settings
    1213    for app in settings.INSTALLED_APPS:
    13         try:
    14             __import__("%s.admin" % app)
    15         except ImportError:
    16             pass
     14        mod = module_or_none(app)
     15        if not mod:
     16            continue
     17        getattr_import('%s.admin' % app)
  • new file django/utils/importutils.py

    diff --git a/django/utils/importutils.py b/django/utils/importutils.py
    new file mode 100644
    index 0000000..8b58d7a
    - +  
     1def getattr_import(module_name):
     2    components = module_name.split('.')
     3    mod = __import__(module_name)
     4    for comp in components[1:]:
     5        mod = getattr(mod, comp)
     6
     7def module_or_none(module_name):
     8    try:
     9        return getattr_import(module_name)
     10    except (ImportError, AttributeError):
     11        return None
     12       
     13 
Back to Top