Ticket #3591: app_labels.6.diff

File app_labels.6.diff, 32.1 KB (added by Vinay Sajip <vinay_sajip@…>, 18 years ago)

An updated patch to cater for recent changes in trunk.

  • django/test/client.py

     
    22import sys
    33from cStringIO import StringIO
    44from urlparse import urlparse
    5 from django.conf import settings
     5from django.conf import settings, get_installed_app_paths
    66from django.contrib.auth import authenticate, login
    77from django.contrib.sessions.models import Session
    88from django.contrib.sessions.middleware import SessionWrapper
     
    128128
    129129    def _session(self):
    130130        "Obtain the current session variables"
    131         if 'django.contrib.sessions' in settings.INSTALLED_APPS:
     131        if 'django.contrib.sessions' in get_installed_app_paths():
    132132            cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
    133133            if cookie:
    134134                return SessionWrapper(cookie.value)
  • django/conf/__init__.py

     
    9797        # of all those apps.
    9898        new_installed_apps = []
    9999        for app in self.INSTALLED_APPS:
    100             if app.endswith('.*'):
     100            if not isinstance(app, basestring) or not app.endswith('.*'):
     101                new_installed_apps.append(app)
     102            else:
    101103                appdir = os.path.dirname(__import__(app[:-2], {}, {}, ['']).__file__)
    102104                for d in os.listdir(appdir):
    103105                    if d.isalpha() and os.path.isdir(os.path.join(appdir, d)):
    104106                        new_installed_apps.append('%s.%s' % (app[:-2], d))
    105             else:
    106                 new_installed_apps.append(app)
    107107        self.INSTALLED_APPS = new_installed_apps
    108108
    109109        if hasattr(time, 'tzset'):
     
    147147    return gettext(*args)
    148148
    149149__builtins__['_'] = first_time_gettext
     150
     151class app(object):
     152    """Configuration directive for specifying an app."""
     153    def __init__(self, path, app_label=None, verbose_name=None):
     154        self.path = path
     155        # if name isn't specified, get the last part of the Python dotted path
     156        self.label = app_label or path.split('.')[-1]
     157        self.verbose_name = verbose_name or self.label
     158        self.app_module = None    # will be filled in by loading.py
     159        self.models_module = None # will be filled in by loading.py
     160
     161    def __repr__(self):
     162        return "<app: %s>" % self.path
     163
     164def get_installed_app_paths():
     165    "Return the paths of all entries in settings.INSTALLED_APPS."
     166    rv = []
     167    for a in settings.INSTALLED_APPS:
     168        if isinstance(a, basestring):
     169            rv.append(a)
     170        else:
     171            rv.append(a.path)
     172    return rv
  • django/db/models/base.py

     
    88from django.db.models.options import Options, AdminOptions
    99from django.db import connection, backend, transaction
    1010from django.db.models import signals
    11 from django.db.models.loading import register_models, get_model
     11from django.db.models.loading import register_models, get_model, get_app_label
    1212from django.dispatch import dispatcher
    1313from django.utils.datastructures import SortedDict
    1414from django.utils.functional import curry
     
    4242                new_class._meta.parents.append(base)
    4343                new_class._meta.parents.extend(base._meta.parents)
    4444
    45 
    4645        if getattr(new_class._meta, 'app_label', None) is None:
    47             # Figure out the app_label by looking one level up.
    48             # For 'django.contrib.sites.models', this would be 'sites'.
    49             model_module = sys.modules[new_class.__module__]
    50             new_class._meta.app_label = model_module.__name__.split('.')[-2]
     46            # Figure out the app_label.
     47            new_class._meta.app_label = get_app_label(new_class)
    5148
    5249        # Bail out early if we have already created this class.
    5350        m = get_model(new_class._meta.app_label, name, False)
  • django/db/models/options.py

     
    1 from django.conf import settings
     1from django.conf import settings, get_installed_app_paths
    22from django.db.models.related import RelatedObject
    33from django.db.models.fields.related import ManyToManyRel
    44from django.db.models.fields import AutoField, FieldDoesNotExist
     
    3636
    3737    def contribute_to_class(self, cls, name):
    3838        cls._meta = self
    39         self.installed = re.sub('\.models$', '', cls.__module__) in settings.INSTALLED_APPS
     39        self.installed = re.sub('\.models$', '', cls.__module__) in get_installed_app_paths()
    4040        # First, construct the default values for these options.
    4141        self.object_name = cls.__name__
    4242        self.module_name = self.object_name.lower()
  • django/db/models/loading.py

     
    11"Utilities for loading models and the modules that contain them."
    22
    3 from django.conf import settings
     3from django.conf import settings, app
    44from django.core.exceptions import ImproperlyConfigured
    55import sys
    66import os
    77
    88__all__ = ('get_apps', 'get_app', 'get_models', 'get_model', 'register_models')
    99
    10 _app_list = []   # Cache of installed apps.
     10_app_list = []   # Cache of installed app instances.
    1111                 # Entry is not placed in app_list cache until entire app is loaded.
    1212_app_models = {} # Dictionary of models against app label
    1313                 # Each value is a dictionary of model name: model class
     
    1515_app_errors = {} # Dictionary of errors that were experienced when loading the INSTALLED_APPS
    1616                 # Key is the app_name of the model, value is the exception that was raised
    1717                 # during model loading.
    18 _loaded = False  # Has the contents of settings.INSTALLED_APPS been loaded?
    19                  # i.e., has get_apps() been called?
     18_app_map = {}    # Map of app instances keyed by app_label.
     19_mod_map = {}    # Map of app instances keyed by app module names.
     20
     21_old_apps = None # what INSTALLED_APPS was when get_apps() was last called
    2022
    2123def get_apps():
    22     "Returns a list of all installed modules that contain models."
     24    "Returns a list of all loaded applications."
    2325    global _app_list
    24     global _loaded
    25     if not _loaded:
    26         _loaded = True
    27         for app_name in settings.INSTALLED_APPS:
     26    global _app_map
     27    global _mod_map
     28    global _old_apps
     29
     30    changed = (_old_apps != settings.INSTALLED_APPS)
     31    if changed:
     32        if changed:
     33            _app_list = []
     34            _app_map = {}
     35            _mod_map = {}
     36        _old_apps = settings.INSTALLED_APPS[:] #Note: making a copy
     37        # We first loop through, setting up the app instances and
     38        # the relevant maps so that we can find the instances by app_label
     39        # or app module name. These need to be ready because we need to be
     40        # able to get the app_label e.g. for applying to model classes.
     41        # If a model class is loaded indirectly without being in an
     42        # installed app, the app_label used will be what it is now - the
     43        # last part of the app module name.
     44        # Note that _app_map and _mod_map will contain entries even
     45        # when an app cannot be loaded by load_app.
     46        for app_entry in settings.INSTALLED_APPS:
     47            if isinstance(app_entry, basestring):
     48                the_app = app(app_entry)
     49            else:
     50                the_app = app_entry
     51            _app_map[the_app.label] = the_app
     52            _mod_map[the_app.path] = the_app
     53
     54        for app_entry in settings.INSTALLED_APPS:
     55            if isinstance(app_entry, basestring):
     56                the_app = _mod_map[app_entry]
     57            else:
     58                the_app = app_entry
     59            app_name = the_app.path
    2860            try:
    2961                load_app(app_name)
     62                _app_list.append(the_app)
    3063            except Exception, e:
    3164                # Problem importing the app
    3265                _app_errors[app_name] = e
    3366    return _app_list
    3467
     68def get_app_label(model_class):
     69    "Returns the app label to be used for a model class."
     70    global _mod_map
     71    key = model_class.__module__
     72    i = key.rfind('.')
     73    assert i > 0, "Model class must be defined in a package sub-module"
     74    key = key[:i]
     75    if key in _mod_map:
     76        rv = _mod_map[key].label
     77    else:
     78        i = key.rfind('.')
     79        if i < 0:
     80            rv = key
     81        else:
     82            rv = key[i + 1:]
     83    return rv
     84
     85def find_app(app_path):
     86    "Find an app instance, given the application path."
     87    get_apps()
     88    return _mod_map[app_path] # _mod_map.get(app_path, None)
     89
    3590def get_app(app_label, emptyOK=False):
    36     "Returns the module containing the models for the given app_label. If the app has no models in it and 'emptyOK' is True, returns None."
     91    "Returns the app instance for the given app_label. If the app has no models in it and 'emptyOK' is True, returns None."
    3792    get_apps() # Run get_apps() to populate the _app_list cache. Slightly hackish.
    38     for app_name in settings.INSTALLED_APPS:
    39         if app_label == app_name.split('.')[-1]:
    40             mod = load_app(app_name)
    41             if mod is None:
    42                 if emptyOK:
    43                     return None
     93    if app_label not in _app_map:
     94        rv = None
    4495            else:
    45                 return mod
     96        rv = _app_map[app_label]
     97    if emptyOK or rv is not None:
     98        return rv
    4699    raise ImproperlyConfigured, "App with label %s could not be found" % app_label
    47100
    48101def load_app(app_name):
    49     "Loads the app with the provided fully qualified name, and returns the model module."
     102    "Loads the app with the provided fully qualified name, and returns the models module."
    50103    global _app_list
     104    global _app_map
     105    global _mod_map
    51106    mod = __import__(app_name, {}, {}, ['models'])
     107    if app_name in _mod_map:
     108        the_app = _mod_map[app_name]
     109    else:
     110        # An app can be loaded by load_app even before get_apps is
     111        # called. In this case, we just make a new app and add it to the maps.
     112        the_app = app(app_name)
     113        _app_map[the_app.label] = the_app
     114        _mod_map[app_name] = the_app
     115        _app_list.append(the_app)
     116    the_app.app_module = mod
    52117    if not hasattr(mod, 'models'):
    53         return None
    54     if mod.models not in _app_list:
    55         _app_list.append(mod.models)
    56     return mod.models
     118        rv = None
     119    else:
     120        rv = mod.models
     121    the_app.models_module = rv
     122    return rv
    57123
    58124def get_app_errors():
    59125    "Returns the map of known problems with the INSTALLED_APPS"
     
    61127    get_apps() # Run get_apps() to populate the _app_list cache. Slightly hackish.
    62128    return _app_errors
    63129
    64 def get_models(app_mod=None):
     130def get_models(the_app=None):
    65131    """
    66     Given a module containing models, returns a list of the models. Otherwise
    67     returns a list of all installed models.
     132    Given an app instance, returns a list of its models. Otherwise
     133    returns a list of all loaded models.
    68134    """
    69     app_list = get_apps() # Run get_apps() to populate the _app_list cache. Slightly hackish.
    70     if app_mod:
    71         return _app_models.get(app_mod.__name__.split('.')[-2], {}).values()
     135    get_apps() # Run get_apps() to populate the _app_list cache. Slightly hackish.
     136    if the_app:
     137        return _app_models.get(the_app.label, {}).values()
    72138    else:
    73139        model_list = []
    74         for app_mod in app_list:
    75             model_list.extend(get_models(app_mod))
     140        for the_app in _app_list:
     141            model_list.extend(get_models(the_app))
    76142        return model_list
    77143
    78144def get_model(app_label, model_name, seed_cache=True):
  • django/db/models/__init__.py

     
    22from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
    33from django.core import validators
    44from django.db import backend, connection
    5 from django.db.models.loading import get_apps, get_app, get_models, get_model, register_models
     5from django.db.models.loading import get_apps, get_app, get_models, get_model, register_models, find_app
    66from django.db.models.query import Q
    77from django.db.models.manager import Manager
    88from django.db.models.base import Model, AdminOptions
  • django/core/management.py

     
    66import os, re, shutil, sys, textwrap
    77from optparse import OptionParser
    88from django.utils import termcolors
     9import logging
     10
     11logger = logging.getLogger("django.core.management")
    912
    1013# For Python 2.3
    1114if not hasattr(__builtins__, 'set'):
     
    368371    from django.conf import settings
    369372
    370373    opts = model._meta
    371     app_dir = os.path.normpath(os.path.join(os.path.dirname(models.get_app(model._meta.app_label).__file__), 'sql'))
     374    app_dir = os.path.normpath(os.path.join(os.path.dirname(models.get_app(model._meta.app_label).models_module.__file__), 'sql'))
    372375    output = []
    373376
    374377    # Some backends can't execute more than one SQL statement at a time,
     
    396399    output = []
    397400
    398401    app_models = get_models(app)
    399     app_dir = os.path.normpath(os.path.join(os.path.dirname(app.__file__), 'sql'))
     402    app_dir = os.path.normpath(os.path.join(os.path.dirname(app.models_module.__file__), 'sql'))
    400403
    401404    for model in app_models:
    402405        output.extend(get_custom_sql_for_model(model))
     
    456459    from django.dispatch import dispatcher
    457460    # Emit the post_sync signal for every application.
    458461    for app in models.get_apps():
    459         app_name = app.__name__.split('.')[-2]
     462        app_name = app.label
    460463        if verbosity >= 2:
    461464            print "Running post-sync handlers for application", app_name
    462465        dispatcher.send(signal=models.signals.post_syncdb, sender=app,
     
    466469def syncdb(verbosity=1, interactive=True):
    467470    "Creates the database tables for all apps in INSTALLED_APPS whose tables haven't already been created."
    468471    from django.db import connection, transaction, models, get_creation_module
    469     from django.conf import settings
     472    from django.conf import settings, get_installed_app_paths
    470473
    471474    disable_termcolors()
    472475
     
    475478
    476479    # Import the 'management' module within each installed app, to register
    477480    # dispatcher events.
    478     for app_name in settings.INSTALLED_APPS:
     481    for app_name in get_installed_app_paths():
    479482        try:
    480483            __import__(app_name + '.management', {}, {}, [''])
    481484        except ImportError:
     
    496499
    497500    # Create the tables for each model
    498501    for app in models.get_apps():
    499         app_name = app.__name__.split('.')[-2]
     502        app_name = app.label
    500503        model_list = models.get_models(app)
    501504        for model in model_list:
    502505            # Create the model's database table, if it doesn't already exist.
     
    519522    # Create the m2m tables. This must be done after all tables have been created
    520523    # to ensure that all referred tables will exist.
    521524    for app in models.get_apps():
    522         app_name = app.__name__.split('.')[-2]
     525        app_name = app.label
    523526        model_list = models.get_models(app)
    524527        for model in model_list:
    525528            if model in created_models:
     
    539542    # Install custom SQL for the app (but only if this
    540543    # is a model we've just created)
    541544    for app in models.get_apps():
    542         app_name = app.__name__.split('.')[-2]
     545        app_name = app.label
    543546        for model in models.get_models(app):
    544547            if model in created_models:
    545548                custom_sql = get_custom_sql_for_model(model)
     
    556559                    else:
    557560                        transaction.commit_unless_managed()
    558561
    559     # Install SQL indicies for all newly created models
     562    # Install SQL indices for all newly created models
    560563    for app in models.get_apps():
    561         app_name = app.__name__.split('.')[-2]
     564        app_name = app.label
    562565        for model in models.get_models(app):
    563566            if model in created_models:
    564567                index_sql = get_sql_indexes_for_model(model)
     
    635638    "Executes the equivalent of 'get_sql_reset' in the current database."
    636639    from django.db import connection, transaction
    637640    from django.conf import settings
    638     app_name = app.__name__.split('.')[-2]
     641    app_name = app.label
    639642
    640643    disable_termcolors()
    641644
     
    676679
    677680def flush(verbosity=1, interactive=True):
    678681    "Returns all tables in the database to the same state they were in immediately after syncdb."
    679     from django.conf import settings
     682    from django.conf import settings, get_installed_app_paths
    680683    from django.db import connection, transaction, models
    681684    from django.dispatch import dispatcher
    682685
     
    687690
    688691    # Import the 'management' module within each installed app, to register
    689692    # dispatcher events.
    690     for app_name in settings.INSTALLED_APPS:
     693    for app_name in get_installed_app_paths():
    691694        try:
    692695            __import__(app_name + '.management', {}, {}, [''])
    693696        except ImportError:
     
    12931296    from django.db.models import get_app, get_apps
    12941297
    12951298    if len(app_labels) == 0:
    1296         app_list = get_apps()
     1299        app_list = [app.models_module for app in get_apps()]
    12971300    else:
    1298         app_list = [get_app(app_label) for app_label in app_labels]
     1301        app_list = [get_app(app_label).models_module for app_label in app_labels]
    12991302
    13001303    test_path = settings.TEST_RUNNER.split('.')
    13011304    # Allow for Python 2.5 relative paths
     
    13401343    transaction.enter_transaction_management()
    13411344    transaction.managed(True)
    13421345
    1343     app_fixtures = [os.path.join(os.path.dirname(app.__file__),'fixtures') for app in get_apps()]
     1346    app_fixtures = []
     1347    for app in get_apps():
     1348        # Some apps (e.g. databrowse) have no models
     1349        if app.models_module:
     1350            app_fixtures.append(os.path.join(os.path.dirname(
     1351                                app.models_module.__file__),'fixtures'))
    13441352    for fixture_label in fixture_labels:
    13451353        parts = fixture_label.split('.')
    13461354        if len(parts) == 1:
     
    13921400                                obj.save()
    13931401                            label_found = True
    13941402                        except Exception, e:
     1403                            logger.exception("Problem installing fixture '%s': %s\n" %
     1404                                     (full_path, str(e)))
    13951405                            fixture.close()
    13961406                            sys.stderr.write(
    13971407                                style.ERROR("Problem installing fixture '%s': %s\n" %
     
    16231633        from django.db import models
    16241634        validate(silent_success=True)
    16251635        try:
    1626             mod_list = [models.get_app(app_label) for app_label in args[1:]]
     1636            app_list = [models.get_app(app_label) for app_label in args[1:]]
    16271637        except ImportError, e:
    16281638            sys.stderr.write(style.ERROR("Error: %s. Are you sure your INSTALLED_APPS setting is correct?\n" % e))
    16291639            sys.exit(1)
    1630         if not mod_list:
     1640        if not app_list:
    16311641            parser.print_usage_and_exit()
    16321642        if action not in NO_SQL_TRANSACTION:
    16331643            print style.SQL_KEYWORD("BEGIN;")
    1634         for mod in mod_list:
     1644        for app in app_list:
    16351645            if action == 'reset':
    1636                 output = action_mapping[action](mod, options.interactive)
     1646                output = action_mapping[action](app, options.interactive)
    16371647            else:
    1638                 output = action_mapping[action](mod)
     1648                output = action_mapping[action](app)
    16391649            if output:
    16401650                print '\n'.join(output)
    16411651        if action not in NO_SQL_TRANSACTION:
  • django/templatetags/__init__.py

     
    1 from django.conf import settings
     1from django.conf import settings, get_installed_app_paths
    22
    3 for a in settings.INSTALLED_APPS:
     3for a in get_installed_app_paths():
    44    try:
    55        __path__.extend(__import__(a + '.templatetags', {}, {}, ['']).__path__)
    66    except ImportError:
  • django/views/i18n.py

     
    11from django import http
    22from django.utils.translation import check_for_language, activate, to_locale, get_language
    33from django.utils.text import javascript_quote
    4 from django.conf import settings
     4from django.conf import settings, get_installed_app_paths
    55import os
    66import gettext as gettext_module
    77
     
    104104        packages = ['django.conf']
    105105    if type(packages) in (str, unicode):
    106106        packages = packages.split('+')
    107     packages = [p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS]
     107    packages = [p for p in packages if p == 'django.conf' or p in get_installed_app_paths()]
    108108    default_locale = to_locale(settings.LANGUAGE_CODE)
    109109    locale = to_locale(get_language())
    110110    t = {}
  • django/contrib/sites/management.py

     
    33"""
    44
    55from django.dispatch import dispatcher
    6 from django.db.models import signals
     6from django.db.models import signals, find_app
    77from django.contrib.sites.models import Site
    8 from django.contrib.sites import models as site_app
    98
    109def create_default_site(app, created_models, verbosity):
    1110    if Site in created_models:
     
    1413        s = Site(domain="example.com", name="example.com")
    1514        s.save()
    1615
    17 dispatcher.connect(create_default_site, sender=site_app, signal=signals.post_syncdb)
     16dispatcher.connect(create_default_site, sender=find_app('django.contrib.sites'), signal=signals.post_syncdb)
  • django/contrib/admin/templatetags/adminapplist.py

     
    1818            app_models = get_models(app)
    1919            if not app_models:
    2020                continue
    21             app_label = app_models[0]._meta.app_label
     21            app_label = app.label
    2222
    2323            has_module_perms = user.has_module_perms(app_label)
    2424
     
    4949                    model_list = [x for key, x in decorated]
    5050
    5151                    app_list.append({
    52                         'name': app_label.title(),
     52                        'name': _(app.verbose_name).title(),
    5353                        'has_module_perms': has_module_perms,
    5454                        'models': model_list,
    5555                    })
  • django/contrib/admin/views/doc.py

     
    159159
    160160    # Get the model class.
    161161    try:
    162         app_mod = models.get_app(app_label)
     162        app = models.get_app(app_label)
    163163    except ImproperlyConfigured:
    164164        raise Http404, _("App %r not found") % app_label
    165165    model = None
    166     for m in models.get_models(app_mod):
     166    for m in models.get_models(app):
    167167        if m._meta.object_name.lower() == model_name:
    168168            model = m
    169169            break
  • django/contrib/auth/management.py

     
    33"""
    44
    55from django.dispatch import dispatcher
    6 from django.db.models import get_models, signals
    7 from django.contrib.auth import models as auth_app
     6from django.db.models import get_models, signals, find_app
    87
    98def _get_permission_codename(action, opts):
    109    return '%s_%s' % (action, opts.object_name.lower())
     
    4645            break
    4746
    4847dispatcher.connect(create_permissions, signal=signals.post_syncdb)
    49 dispatcher.connect(create_superuser, sender=auth_app, signal=signals.post_syncdb)
     48dispatcher.connect(create_superuser, sender=find_app('django.contrib.auth'), signal=signals.post_syncdb)
  • django/utils/translation/trans_real.py

     
    107107    if t is not None:
    108108        return t
    109109
    110     from django.conf import settings
     110    from django.conf import settings, get_installed_app_paths
    111111
    112112    # set up the right translation class
    113113    klass = DjangoTranslation
     
    160160        if projectpath and os.path.isdir(projectpath):
    161161            res = _merge(projectpath)
    162162
    163         for appname in settings.INSTALLED_APPS:
     163        for appname in get_installed_app_paths():
    164164            p = appname.rfind('.')
    165165            if p >= 0:
    166166                app = getattr(__import__(appname[:p], {}, {}, [appname[p+1:]]), appname[p+1:])
  • django/bin/make-messages.py

     
    129129                print "errors happened while running msguniq"
    130130                print errors
    131131                sys.exit(8)
     132            # Try importing the local settings. This will work if you're
     133            # in the project directory
     134            sys.path.insert(0, '.')
     135            try:
     136                import settings
     137                apps = settings.INSTALLED_APPS
     138            except (ImportError, AttributeError):
     139                apps = []
     140            del sys.path[0]
     141            # Now look for all applications which have a verbose name
     142            # which is different from the default. If different, add
     143            # an internationalization string.
     144            for app in apps:
     145                if (not isinstance(app, basestring)) and (app.verbose_name != app.path.split('.')[-1]):
     146                    s = '\nmsgid "%s"\nmsgstr ""\n' % app.verbose_name
     147                    msgs += s
    132148            open(potfile, 'w').write(msgs)
    133149            if os.path.exists(pofile):
    134150                (stdin, stdout, stderr) = os.popen3('msgmerge -q "%s" "%s"' % (pofile, potfile), 'b')
  • django/template/loaders/app_directories.py

     
    11# Wrapper for loading templates from "template" directories in installed app packages.
    22
    3 from django.conf import settings
     3from django.conf import settings, get_installed_app_paths
    44from django.core.exceptions import ImproperlyConfigured
    55from django.template import TemplateDoesNotExist
    66import os
    77
    88# At compile time, cache the directories to search.
    99app_template_dirs = []
    10 for app in settings.INSTALLED_APPS:
     10for app in get_installed_app_paths():
    1111    i = app.rfind('.')
    1212    if i == -1:
    1313        m, a = app, None
  • django/template/loaders/eggs.py

     
    66    resource_string = None
    77
    88from django.template import TemplateDoesNotExist
    9 from django.conf import settings
     9from django.conf import settings, get_installed_app_paths
    1010
    1111def load_template_source(template_name, template_dirs=None):
    1212    """
     
    1616    """
    1717    if resource_string is not None:
    1818        pkg_name = 'templates/' + template_name
    19         for app in settings.INSTALLED_APPS:
     19        for app in get_installed_app_paths():
    2020            try:
    2121                return (resource_string(app, pkg_name), 'egg:%s:%s ' % (app, pkg_name))
    2222            except:
  • tests/runtests.py

     
    22
    33import os, sys, traceback
    44import unittest
     5from django.conf import app, get_installed_app_paths
    56
    67import django.contrib as contrib
    78CONTRIB_DIR_NAME = 'django.contrib'
     
    1718
    1819ALWAYS_INSTALLED_APPS = [
    1920    'django.contrib.contenttypes',
    20     'django.contrib.auth',
     21    #We need to use the same app label, otherwise fixtures will break...
     22    app('django.contrib.auth', 'auth', 'Authentication'),
    2123    'django.contrib.sites',
    2224    'django.contrib.flatpages',
    2325    'django.contrib.redirects',
     
    5254
    5355    def runTest(self):
    5456        from django.core import management
    55         from django.db.models.loading import load_app
     57        from django.db.models.loading import load_app, find_app
    5658        from cStringIO import StringIO
    5759
    5860        try:
    5961            module = load_app(self.model_label)
    6062        except Exception, e:
    61             self.fail('Unable to load invalid model module')
     63            self.fail('Unable to load invalid application %s: %s' % (self.model_label, e))
    6264
    6365        s = StringIO()
    64         count = management.get_validation_errors(s, module)
     66        count = management.get_validation_errors(s, find_app(self.model_label))
    6567        s.seek(0)
    6668        error_log = s.read()
    6769        actual = error_log.split('\n')
     
    114116                    print "Importing model %s" % model_name
    115117                mod = load_app(model_label)
    116118                if mod:
    117                     if model_label not in settings.INSTALLED_APPS:
     119                    if model_label not in get_installed_app_paths():
    118120                        settings.INSTALLED_APPS.append(model_label)
    119121                    test_models.append(mod)
    120122        except Exception, e:
  • docs/settings.txt

     
    469469
    470470Default: ``()`` (Empty tuple)
    471471
    472 A tuple of strings designating all applications that are enabled in this Django
    473 installation. Each string should be a full Python path to a Python package that
    474 contains a Django application, as created by `django-admin.py startapp`_.
     472A tuple of entries designating all applications that are enabled in this Django
     473installation. Each entry should be one of the following:
     474
     475    * A string which is a full Python path to a Python package that contains a
     476      Django application, as created by `django-admin.py startapp`_.
     477    * A string which is a full Python path to a Python package which contains
     478      multiple applications, with an appended ``.*``. This entry is replaced
     479      by entries for the contained applications. For example, a wildcard
     480      entry of the form ``django.contrib.*`` would be replaced by
     481      multiple entries for ``django.contrib.admin``, ``django.contrib.auth``
     482      etc.
     483    * An ``app`` configuration directive (to use it, you need to add
     484      ``from django.conf import app`` to your ``settings`` file). This takes
     485      the form ``app(path, label=None, verbose_name=None)``. The ``path``
     486      argument must specify the full Python path to a Python package that
     487      contains a Django application. The ``label`` argument, if specified,
     488      provides a unique application label (used to disambiguate different
     489      third-party applications with conflicting default label values). If this
     490      value is not specified, the last portion of the application path is used
     491      as the default label. The ``verbose_name`` argument, if specified, is
     492      used to provide a descriptive name for the application in the admin
     493      screens. If this value is not specified, the last portion of the
     494      application path is used as the default value.
    475495
    476496.. _django-admin.py startapp: ../django-admin/#startapp-appname
    477497
Back to Top