Login

Generic Autodiscovery

Author:
coleifer
Posted:
April 4, 2011
Language:
Python
Version:
Not specified
Score:
2 (after 4 ratings)

Admin-like autodiscover for your apps.

I have copy/pasted this code too many times...Dynamically autodiscover a particular module_name in a django project's INSTALLED_APPS directories, a-la django admin's autodiscover() method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def generic_autodiscover(module_name):
    """
    I have copy/pasted this code too many times...Dynamically autodiscover a
    particular module_name in a django project's INSTALLED_APPS directories,
    a-la django admin's autodiscover() method.
    
    Usage:
        generic_autodiscover('commands') <-- find all commands.py and load 'em
    """
    import imp
    from django.conf import settings

    for app in settings.INSTALLED_APPS:
        try:
            import_module(app)
            app_path = sys.modules[app].__path__
        except AttributeError:
            continue
        try:
            imp.find_module(module_name, app_path)
        except ImportError:
            continue
        import_module('%s.%s' % (app, module_name))
        app_path = sys.modules['%s.%s' % (app, module_name)]

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

michaelmior (on January 4, 2013):

The body of the method can be simplified to the following. I don't think it's necessary to catch exceptions from importing apps (the server will fail to start if this happens anyway). find_module is also not necessary.

from django.conf import settings
from django.utils.importlib import import_module

for app in settings.INSTALLED_APPS:
    try:
        import_module('%s.%s' % (app, module_name))
    except:
        continue

#

bakatrouble (on December 9, 2016):

There is a django.utils.module_loading.autodiscover_modules now

#

Please login first before commenting.