Ticket #3591: app_labels.13.diff

File app_labels.13.diff, 36.9 KB (added by Vinay Sajip <vinay_sajip@…>, 15 years ago)

Patch updated to apply cleanly to r10759.

  • django/test/simple.py

     
    176176                suite.addTest(build_test(label))
    177177            else:
    178178                app = get_app(label)
    179                 suite.addTest(build_suite(app))
     179                mod = app.models_module
     180                if mod:
     181                  suite.addTest(build_suite(mod))
    180182    else:
    181183        for app in get_apps():
    182             suite.addTest(build_suite(app))
    183 
     184            mod = app.models_module
     185            if mod:
     186                suite.addTest(build_suite(mod))
     187   
    184188    for test in extra_tests:
    185189        suite.addTest(test)
    186190
  • django/test/client.py

     
    88except ImportError:
    99    from StringIO import StringIO
    1010
    11 from django.conf import settings
     11from django.conf import settings, get_installed_app_paths
    1212from django.contrib.auth import authenticate, login
    1313from django.core.handlers.base import BaseHandler
    1414from django.core.handlers.wsgi import WSGIRequest
     
    177177        """
    178178        Obtains the current session variables.
    179179        """
    180         if 'django.contrib.sessions' in settings.INSTALLED_APPS:
     180        if 'django.contrib.sessions' in get_installed_app_paths():
    181181            engine = import_module(settings.SESSION_ENGINE)
    182182            cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
    183183            if cookie:
     
    406406        """
    407407        user = authenticate(**credentials)
    408408        if user and user.is_active \
    409                 and 'django.contrib.sessions' in settings.INSTALLED_APPS:
     409                and 'django.contrib.sessions' in get_installed_app_paths():
    410410            engine = import_module(settings.SESSION_ENGINE)
    411411
    412412            # Create a fake request to store login details.
  • django/db/models/base.py

     
    1717from django.db.models.options import Options
    1818from django.db import connection, transaction, DatabaseError
    1919from django.db.models import signals
    20 from django.db.models.loading import register_models, get_model
     20from django.db.models.loading import register_models, get_model, get_app_label
    2121from django.utils.functional import curry
    2222from django.utils.encoding import smart_str, force_unicode, smart_unicode
    2323from django.conf import settings
     
    8282                new_class._default_manager = new_class._default_manager._copy_to_model(new_class)
    8383                new_class._base_manager = new_class._base_manager._copy_to_model(new_class)
    8484
     85        if getattr(new_class._meta, 'app_label', None) is None:
     86            # Figure out the app_label.
     87            new_class._meta.app_label = get_app_label(new_class)
     88
    8589        # Bail out early if we have already created this class.
    8690        m = get_model(new_class._meta.app_label, name, False)
    8791        if m is not None:
  • django/db/models/options.py

     
    55except NameError:
    66    from sets import Set as set     # Python 2.3 fallback
    77
    8 from django.conf import settings
     8from django.conf import settings, get_installed_app_paths
    99from django.db.models.related import RelatedObject
    1010from django.db.models.fields.related import ManyToManyRel
    1111from django.db.models.fields import AutoField, FieldDoesNotExist
     
    5858        from django.db.backends.util import truncate_name
    5959
    6060        cls._meta = self
    61         self.installed = re.sub('\.models$', '', cls.__module__) in settings.INSTALLED_APPS
     61        self.installed = re.sub('\.models$', '', cls.__module__) in get_installed_app_paths()
    6262        # First, construct the default values for these options.
    6363        self.object_name = cls.__name__
    6464        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
    55from django.utils.datastructures import SortedDict
    66from django.utils.importlib import import_module
    77
    88import sys
    9 import os
     9import os, os.path
    1010import threading
    1111
    1212__all__ = ('get_apps', 'get_app', 'get_models', 'get_model', 'register_models',
    13         'load_app', 'app_cache_ready')
     13        'load_app', 'app_cache_ready', 'find_app')
    1414
    1515class AppCache(object):
    1616    """
     
    2929        # Mapping of app_labels to errors raised when trying to import the app.
    3030        app_errors = {},
    3131
     32
     33        # Mapping of app_labels to app instances.
     34        app_map = {},
     35
     36        # Mapping of app module names to app instances.
     37        mod_map = {},
     38
     39        # List of app instances.
     40        app_instances = [],
     41
    3242        # -- Everything below here is only used when populating the cache --
    3343        loaded = False,
    3444        handled = {},
     
    5262        try:
    5363            if self.loaded:
    5464                return
    55             for app_name in settings.INSTALLED_APPS:
     65            # We first loop through, setting up the app instances and
     66            # the relevant maps so that we can find the instances by app_label
     67            # or app module name. These need to be ready because we need to be
     68            # able to get the app_label e.g. for applying to model classes.
     69            # If a model class is loaded indirectly without being in an
     70            # installed app, the app_label used will be what it is now - the
     71            # last part of the app module name.
     72            # Note that app_map and mod_map will contain entries even
     73            # when an app cannot be loaded by load_app.
     74            for app_entry in settings.INSTALLED_APPS:
     75                if isinstance(app_entry, basestring):
     76                    the_app = app(app_entry)
     77                else:
     78                    the_app = app_entry
     79                self.app_map[the_app.label] = the_app
     80                self.mod_map[the_app.path] = the_app
     81
     82            for app_entry in settings.INSTALLED_APPS:
     83                if isinstance(app_entry, basestring):
     84                    the_app = self.mod_map[app_entry]
     85                else:
     86                    the_app = app_entry
     87                app_name = the_app.path
    5688                if app_name in self.handled:
    5789                    continue
    58                 self.load_app(app_name, True)
     90                try:
     91                    self.load_app(app_name, True)
     92                    self.app_instances.append(the_app)
     93                except Exception, e:
     94                    # Problem importing the app
     95                    self.app_errors[app_name] = e
    5996            if not self.nesting_level:
    6097                for app_name in self.postponed:
     98                    the_app = self.mod_map[app_name]
    6199                    self.load_app(app_name)
     100                    self.app_instances.append(the_app)                   
    62101                self.loaded = True
    63102        finally:
    64103            self.write_lock.release()
     
    70109        """
    71110        self.handled[app_name] = None
    72111        self.nesting_level += 1
     112        mod = import_module(app_name)
     113        if app_name in self.mod_map:
     114            the_app = self.mod_map[app_name]
     115        else:
     116            # An app can be loaded by load_app even before get_apps is
     117            # called. In this case, we just make a new app and add it to the maps.
     118            the_app = app(app_name)
     119            self.app_map[the_app.label] = the_app
     120            self.mod_map[app_name] = the_app
     121            self.app_instances.append(the_app)
     122        the_app.app_module = mod
    73123        try:
    74124            models = import_module('.models', app_name)
     125            the_app.models_module = models
    75126        except ImportError:
    76127            self.nesting_level -= 1
    77128            if can_postpone:
     
    104155        # list page, for example.
    105156        apps = [(v, k) for k, v in self.app_store.items()]
    106157        apps.sort()
    107         return [elt[1] for elt in apps]
     158        #return [elt[1] for elt in apps]
     159        return self.app_instances
    108160
     161    def get_app_label(self, model_class):
     162        "Returns the app label to be used for a model class."
     163        key = model_class.__module__
     164        i = key.rfind('.')
     165        assert i > 0, "Model class must be defined in a package sub-module"
     166        key = key[:i]
     167        if key in self.mod_map:
     168            rv = self.mod_map[key].label
     169        else:
     170            i = key.rfind('.')
     171            if i < 0:
     172                rv = key
     173            else:
     174                rv = key[i + 1:]
     175        return rv
     176   
     177    def find_app(self, app_path):
     178        "Find an app instance, given the application path."
     179        self._populate()
     180        return self.mod_map[app_path]
     181
    109182    def get_app(self, app_label, emptyOK=False):
    110183        """
    111         Returns the module containing the models for the given app_label. If
     184        Returns the app instance for the given app_label. If
    112185        the app has no models in it and 'emptyOK' is True, returns None.
    113186        """
    114187        self._populate()
    115         self.write_lock.acquire()
    116         try:
    117             for app_name in settings.INSTALLED_APPS:
    118                 if app_label == app_name.split('.')[-1]:
    119                     mod = self.load_app(app_name, False)
    120                     if mod is None:
    121                         if emptyOK:
    122                             return None
    123                     else:
    124                         return mod
    125             raise ImproperlyConfigured, "App with label %s could not be found" % app_label
    126         finally:
    127             self.write_lock.release()
     188        if app_label not in self.app_map:
     189            rv = None
     190        else:
     191            rv = self.app_map[app_label]
     192        if emptyOK or rv is not None:
     193            return rv
     194        raise ImproperlyConfigured, "App with label %s could not be found" % app_label
    128195
    129196    def get_app_errors(self):
    130197        "Returns the map of known problems with the INSTALLED_APPS."
    131198        self._populate()
    132199        return self.app_errors
    133200
    134     def get_models(self, app_mod=None):
     201    def get_models(self, the_app=None):
    135202        """
    136         Given a module containing models, returns a list of the models.
     203        Given an app instance, returns a list of its models.
    137204        Otherwise returns a list of all installed models.
    138205        """
    139206        self._populate()
    140         if app_mod:
    141             return self.app_models.get(app_mod.__name__.split('.')[-2], SortedDict()).values()
     207        if the_app:
     208            return self.app_models.get(the_app.label, SortedDict()).values()
    142209        else:
    143210            model_list = []
    144             for app_entry in self.app_models.itervalues():
    145                 model_list.extend(app_entry.values())
     211            for the_app in self.app_instances:
     212                model_list.extend(get_models(the_app))
    146213            return model_list
    147214
    148215    def get_model(self, app_label, model_name, seed_cache=True):
     
    190257register_models = cache.register_models
    191258load_app = cache.load_app
    192259app_cache_ready = cache.app_cache_ready
     260find_app = cache.find_app
     261get_app_label = cache.get_app_label
  • django/db/models/__init__.py

     
    11from django.conf import settings
    22from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
    33from django.db import connection
    4 from django.db.models.loading import get_apps, get_app, get_models, get_model, register_models
     4from django.db.models.loading import get_apps, get_app, get_models, get_model, register_models, find_app
    55from django.db.models.query import Q
    66from django.db.models.expressions import F
    77from django.db.models.manager import Manager
  • django/conf/__init__.py

     
    8989        # of all those apps.
    9090        new_installed_apps = []
    9191        for app in self.INSTALLED_APPS:
    92             if app.endswith('.*'):
     92            if not isinstance(app, basestring) or not app.endswith('.*'):
     93                new_installed_apps.append(app)
     94            else:
    9395                app_mod = importlib.import_module(app[:-2])
    9496                appdir = os.path.dirname(app_mod.__file__)
    9597                app_subdirs = os.listdir(appdir)
     
    98100                for d in app_subdirs:
    99101                    if name_pattern.match(d) and os.path.isdir(os.path.join(appdir, d)):
    100102                        new_installed_apps.append('%s.%s' % (app[:-2], d))
    101             else:
    102                 new_installed_apps.append(app)
    103103        self.INSTALLED_APPS = new_installed_apps
    104104
    105105        if hasattr(time, 'tzset'):
     
    134134
    135135settings = LazySettings()
    136136
     137class app(object):
     138    """Configuration directive for specifying an app."""
     139    def __init__(self, path, app_label=None, verbose_name=None):
     140        self.path = path
     141        # if name isn't specified, get the last part of the Python dotted path
     142        self.label = app_label or path.split('.')[-1]
     143        self.verbose_name = verbose_name or self.label
     144        self.app_module = None    # will be filled in by loading.py
     145        self.models_module = None # will be filled in by loading.py
     146
     147    def __repr__(self):
     148        return "<app: %s>" % self.path
     149
     150def get_installed_app_paths():
     151    "Return the paths of all entries in settings.INSTALLED_APPS."
     152    rv = []
     153    for a in settings.INSTALLED_APPS:
     154        if isinstance(a, basestring):
     155            rv.append(a)
     156        else:
     157            rv.append(a.path)
     158    return rv
  • django/core/management/commands/loaddata.py

     
    7676        if has_bz2:
    7777            compression_types['bz2'] = bz2.BZ2File
    7878
    79         app_fixtures = [os.path.join(os.path.dirname(app.__file__), 'fixtures') for app in get_apps()]
     79        app_fixtures = [os.path.join(os.path.dirname(app.app_module.__file__), 'fixtures') for app in get_apps() if app.app_module]
    8080        for fixture_label in fixture_labels:
    8181            parts = fixture_label.split('.')
    8282
  • django/core/management/commands/flush.py

     
     1from django.conf import get_installed_app_paths
    12from django.core.management.base import NoArgsCommand, CommandError
    23from django.core.management.color import no_style
    34from django.utils.importlib import import_module
     
    2223
    2324        # Import the 'management' module within each installed app, to register
    2425        # dispatcher events.
    25         for app_name in settings.INSTALLED_APPS:
     26        for app_name in get_installed_app_paths():
    2627            try:
    2728                import_module('.management', app_name)
    2829            except ImportError:
  • django/core/management/commands/syncdb.py

     
     1from django.conf import get_installed_app_paths
    12from django.core.management.base import NoArgsCommand
    23from django.core.management.color import no_style
    34from django.utils.importlib import import_module
     
    2930
    3031        # Import the 'management' module within each installed app, to register
    3132        # dispatcher events.
    32         for app_name in settings.INSTALLED_APPS:
     33        for app_name in get_installed_app_paths():
    3334            try:
    3435                import_module('.management', app_name)
    3536            except ImportError, exc:
     
    5657
    5758        # Create the tables for each model
    5859        for app in models.get_apps():
    59             app_name = app.__name__.split('.')[-2]
     60            app_name = app.label
    6061            model_list = models.get_models(app)
    6162            for model in model_list:
    6263                # Create the model's database table, if it doesn't already exist.
     
    8182        # Create the m2m tables. This must be done after all tables have been created
    8283        # to ensure that all referred tables will exist.
    8384        for app in models.get_apps():
    84             app_name = app.__name__.split('.')[-2]
     85            app_name = app.label
    8586            model_list = models.get_models(app)
    8687            for model in model_list:
    8788                if model in created_models:
     
    104105        # Install custom SQL for the app (but only if this
    105106        # is a model we've just created)
    106107        for app in models.get_apps():
    107             app_name = app.__name__.split('.')[-2]
     108            app_name = app.label
    108109            for model in models.get_models(app):
    109110                if model in created_models:
    110111                    custom_sql = custom_sql_for_model(model, self.style)
     
    128129                            print "No custom SQL for %s.%s model" % (app_name, model._meta.object_name)
    129130        # Install SQL indicies for all newly created models
    130131        for app in models.get_apps():
    131             app_name = app.__name__.split('.')[-2]
     132            app_name = app.label
    132133            for model in models.get_models(app):
    133134                if model in created_models:
    134135                    index_sql = connection.creation.sql_indexes_for_model(model, self.style)
  • django/core/management/__init__.py

     
    9797
    9898        # Find the installed apps
    9999        try:
    100             from django.conf import settings
    101             apps = settings.INSTALLED_APPS
     100            from django.conf import settings, get_installed_app_paths
     101            apps = get_installed_app_paths()
    102102        except (AttributeError, EnvironmentError, ImportError):
    103103            apps = []
    104104
  • django/core/management/sql.py

     
    137137    output = []
    138138
    139139    app_models = get_models(app)
    140     app_dir = os.path.normpath(os.path.join(os.path.dirname(app.__file__), 'sql'))
     140    app_dir = os.path.normpath(os.path.join(os.path.dirname(app.app_module.__file__), 'sql'))
    141141
    142142    for model in app_models:
    143143        output.extend(custom_sql_for_model(model, style))
     
    161161    from django.conf import settings
    162162
    163163    opts = model._meta
    164     app_dir = os.path.normpath(os.path.join(os.path.dirname(models.get_app(model._meta.app_label).__file__), 'sql'))
     164    app_dir = os.path.normpath(os.path.join(os.path.dirname(models.get_app(model._meta.app_label).app_module.__file__), 'sql'))
    165165    output = []
    166166
    167167    # Post-creation SQL should come before any initial SQL data is loaded.
     
    197197    from django.dispatch import dispatcher
    198198    # Emit the post_sync signal for every application.
    199199    for app in models.get_apps():
    200         app_name = app.__name__.split('.')[-2]
     200        app_name = app.label
    201201        if verbosity >= 2:
    202202            print "Running post-sync handlers for application", app_name
    203203        models.signals.post_syncdb.send(sender=app, app=app,
  • django/templatetags/__init__.py

     
    1 from django.conf import settings
     1from django.conf import settings, get_installed_app_paths
    22from django.utils import importlib
    33
    4 for a in settings.INSTALLED_APPS:
     4for a in get_installed_app_paths():
    55    try:
    66        __path__.extend(importlib.import_module('.templatetags', a).__path__)
    77    except ImportError:
  • django/views/i18n.py

     
    11from django import http
    2 from django.conf import settings
     2from django.conf import settings, get_installed_app_paths
    33from django.utils import importlib
    44from django.utils.translation import check_for_language, activate, to_locale, get_language
    55from django.utils.text import javascript_quote
     
    122122        packages = ['django.conf']
    123123    if type(packages) in (str, unicode):
    124124        packages = packages.split('+')
    125     packages = [p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS]
     125    packages = [p for p in packages if p == 'django.conf' or p in get_installed_app_paths()]
    126126    default_locale = to_locale(settings.LANGUAGE_CODE)
    127127    locale = to_locale(get_language())
    128128    t = {}
  • django/contrib/comments/__init__.py

     
    1 from django.conf import settings
     1from django.conf import settings, get_installed_app_paths
    22from django.core import urlresolvers
    33from django.core.exceptions import ImproperlyConfigured
    44from django.contrib.comments.models import Comment
     
    1313    """
    1414    # Make sure the app's in INSTALLED_APPS
    1515    comments_app = get_comment_app_name()
    16     if comments_app not in settings.INSTALLED_APPS:
     16    if comments_app not in get_installed_app_paths():
    1717        raise ImproperlyConfigured("The COMMENTS_APP (%r) "\
    1818                                   "must be in INSTALLED_APPS" % settings.COMMENTS_APP)
    1919
  • django/contrib/sites/management.py

     
    22Creates the default Site object.
    33"""
    44
    5 from django.db.models import signals
     5from django.db.models import signals, find_app
    66from django.contrib.sites.models import Site
    7 from django.contrib.sites import models as site_app
    87
    98def create_default_site(app, created_models, verbosity, **kwargs):
    109    if Site in created_models:
     
    1413        s.save()
    1514    Site.objects.clear_cache()
    1615
    17 signals.post_syncdb.connect(create_default_site, sender=site_app)
     16signals.post_syncdb.connect(create_default_site, sender=find_app('django.contrib.sites'))
  • django/contrib/admin/options.py

     
    88from django.contrib.admin.util import unquote, flatten_fieldsets, get_deleted_objects, model_ngettext, model_format_dict
    99from django.core.exceptions import PermissionDenied
    1010from django.db import models, transaction
     11from django.db.models import get_app
    1112from django.db.models.fields import BLANK_CHOICE_DASH
    1213from django.http import Http404, HttpResponse, HttpResponseRedirect
    1314from django.shortcuts import get_object_or_404, render_to_response
     
    777778            'inline_admin_formsets': inline_admin_formsets,
    778779            'errors': helpers.AdminErrorList(form, formsets),
    779780            'root_path': self.admin_site.root_path,
    780             'app_label': opts.app_label,
     781            'app_label': get_app(opts.app_label).verbose_name,
    781782        }
    782783        context.update(extra_context or {})
    783784        return self.render_change_form(request, context, form_url=form_url, add=True)
     
    866867            'inline_admin_formsets': inline_admin_formsets,
    867868            'errors': helpers.AdminErrorList(form, formsets),
    868869            'root_path': self.admin_site.root_path,
    869             'app_label': opts.app_label,
     870            'app_label': get_app(opts.app_label).verbose_name,
    870871        }
    871872        context.update(extra_context or {})
    872873        return self.render_change_form(request, context, change=True, obj=obj)
     
    971972            'media': media,
    972973            'has_add_permission': self.has_add_permission(request),
    973974            'root_path': self.admin_site.root_path,
    974             'app_label': app_label,
     975            'app_label': get_app(app_label).verbose_name,
    975976            'action_form': action_form,
    976977            'actions_on_top': self.actions_on_top,
    977978            'actions_on_bottom': self.actions_on_bottom,
     
    10291030            "perms_lacking": perms_needed,
    10301031            "opts": opts,
    10311032            "root_path": self.admin_site.root_path,
    1032             "app_label": app_label,
     1033            "app_label": get_app(app_label).verbose_name,
    10331034        }
    10341035        context.update(extra_context or {})
    10351036        return render_to_response(self.delete_confirmation_template or [
     
    10561057            'module_name': capfirst(force_unicode(opts.verbose_name_plural)),
    10571058            'object': obj,
    10581059            'root_path': self.admin_site.root_path,
    1059             'app_label': app_label,
     1060            'app_label': get_app(app_label).verbose_name,
    10601061        }
    10611062        context.update(extra_context or {})
    10621063        return render_to_response(self.object_history_template or [
  • django/contrib/admin/__init__.py

     
    2525    LOADING = True
    2626
    2727    import imp
    28     from django.conf import settings
     28    from django.conf import settings, get_installed_app_paths
    2929
    30     for app in settings.INSTALLED_APPS:
     30    for app in get_installed_app_paths():
    3131        # For each app, we need to look for an admin.py inside that app's
    3232        # package. We can't use os.path here -- recall that modules may be
    3333        # imported different ways (think zip files) -- so we need to get
  • django/contrib/admin/sites.py

     
    33from django.contrib.admin import ModelAdmin
    44from django.contrib.admin import actions
    55from django.contrib.auth import authenticate, login
     6from django.db.models import get_app
    67from django.db.models.base import ModelBase
    78from django.core.exceptions import ImproperlyConfigured
    89from django.shortcuts import render_to_response
     
    342343                        app_dict[app_label]['models'].append(model_dict)
    343344                    else:
    344345                        app_dict[app_label] = {
    345                             'name': app_label.title(),
     346                            'name': get_app(app_label).verbose_name,
    346347                            'app_url': app_label + '/',
    347348                            'has_module_perms': has_module_perms,
    348349                            'models': [model_dict],
     
    404405                            # something to display, add in the necessary meta
    405406                            # information.
    406407                            app_dict = {
    407                                 'name': app_label.title(),
     408                                'name': get_app(app_label).verbose_name,
    408409                                'app_url': '',
    409410                                'has_module_perms': has_module_perms,
    410411                                'models': [model_dict],
     
    414415        # Sort the models alphabetically within each app.
    415416        app_dict['models'].sort(lambda x, y: cmp(x['name'], y['name']))
    416417        context = {
    417             'title': _('%s administration') % capfirst(app_label),
     418            'title': _('%s administration') % get_app(app_label).verbose_name,
    418419            'app_list': [app_dict],
    419420            'root_path': self.root_path,
    420421        }
  • django/contrib/contenttypes/management.py

     
    88    entries that no longer have a matching model class.
    99    """
    1010    ContentType.objects.clear_cache()
    11     content_types = list(ContentType.objects.filter(app_label=app.__name__.split('.')[-2]))
     11    content_types = list(ContentType.objects.filter(app_label=app.label))
    1212    app_models = get_models(app)
    1313    if not app_models:
    1414        return
  • django/contrib/auth/management/__init__.py

     
    22Creates permissions for all installed apps that need permissions.
    33"""
    44
    5 from django.db.models import get_models, signals
    6 from django.contrib.auth import models as auth_app
     5from django.db.models import get_models, signals, find_app
    76
    87def _get_permission_codename(action, opts):
    98    return u'%s_%s' % (action, opts.object_name.lower())
     
    4746signals.post_syncdb.connect(create_permissions,
    4847    dispatch_uid = "django.contrib.auth.management.create_permissions")
    4948signals.post_syncdb.connect(create_superuser,
    50     sender=auth_app, dispatch_uid = "django.contrib.auth.management.create_superuser")
     49    sender=find_app('django.contrib.auth'),
     50    dispatch_uid = "django.contrib.auth.management.create_superuser")
  • django/utils/translation/trans_real.py

     
    115115    if t is not None:
    116116        return t
    117117
    118     from django.conf import settings
     118    from django.conf import settings, get_installed_app_paths
    119119
    120120    # set up the right translation class
    121121    klass = DjangoTranslation
     
    176176        if projectpath and os.path.isdir(projectpath):
    177177            res = _merge(projectpath)
    178178
    179         for appname in settings.INSTALLED_APPS:
     179        for appname in get_installed_app_paths():
    180180            app = import_module(appname)
    181181            apppath = os.path.join(os.path.dirname(app.__file__), 'locale')
    182182
  • django/template/loaders/app_directories.py

     
    66import os
    77import sys
    88
    9 from django.conf import settings
     9from django.conf import settings, get_installed_app_paths
    1010from django.core.exceptions import ImproperlyConfigured
    1111from django.template import TemplateDoesNotExist
    1212from django.utils._os import safe_join
     
    1515# At compile time, cache the directories to search.
    1616fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
    1717app_template_dirs = []
    18 for app in settings.INSTALLED_APPS:
     18for app in get_installed_app_paths():
    1919    try:
    2020        mod = import_module(app)
    2121    except ImportError, e:
  • 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).decode(settings.FILE_CHARSET), 'egg:%s:%s' % (app, pkg_name))
    2222            except:
  • tests/regressiontests/admin_scripts/tests.py

     
    10411041        args = ['app_command', 'auth']
    10421042        out, err = self.run_manage(args)
    10431043        self.assertNoOutput(err)
    1044         self.assertOutput(out, "EXECUTE:AppCommand app=<module 'django.contrib.auth.models'")
    1045         self.assertOutput(out, os.sep.join(['django','contrib','auth','models.py']))
    1046         self.assertOutput(out, "'>, options=[('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]")
     1044        self.assertOutput(out, "EXECUTE:AppCommand app=<app: django.contrib.auth>")
     1045        #self.assertOutput(out, os.sep.join(['django','contrib','auth','models.py']))
     1046        self.assertOutput(out, ">, options=[('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]")
    10471047
    10481048    def test_app_command_no_apps(self):
    10491049        "User AppCommands raise an error when no app name is provided"
     
    10561056        args = ['app_command','auth','contenttypes']
    10571057        out, err = self.run_manage(args)
    10581058        self.assertNoOutput(err)
    1059         self.assertOutput(out, "EXECUTE:AppCommand app=<module 'django.contrib.auth.models'")
    1060         self.assertOutput(out, os.sep.join(['django','contrib','auth','models.py']))
    1061         self.assertOutput(out, "'>, options=[('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]")
    1062         self.assertOutput(out, "EXECUTE:AppCommand app=<module 'django.contrib.contenttypes.models'")
    1063         self.assertOutput(out, os.sep.join(['django','contrib','contenttypes','models.py']))
    1064         self.assertOutput(out, "'>, options=[('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]")
     1059        self.assertOutput(out, "EXECUTE:AppCommand app=<app: django.contrib.auth>")
     1060        #self.assertOutput(out, os.sep.join(['django','contrib','auth','models.py']))
     1061        self.assertOutput(out, ">, options=[('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]")
     1062        self.assertOutput(out, "EXECUTE:AppCommand app=<app: django.contrib.contenttypes>")
     1063        #self.assertOutput(out, os.sep.join(['django','contrib','contenttypes','models.py']))
     1064        self.assertOutput(out, ">, options=[('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]")
    10651065
    10661066    def test_app_command_invalid_appname(self):
    10671067        "User AppCommands can execute when a single app name is provided"
  • 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
    78
     
    2324
    2425ALWAYS_INSTALLED_APPS = [
    2526    'django.contrib.contenttypes',
    26     'django.contrib.auth',
     27    #We need to use the same app label, otherwise fixtures will break...
     28    app('django.contrib.auth', 'auth', 'Authentication'),
    2729    'django.contrib.sites',
    2830    'django.contrib.flatpages',
    2931    'django.contrib.redirects',
     
    5860
    5961    def runTest(self):
    6062        from django.core.management.validation import get_validation_errors
    61         from django.db.models.loading import load_app
     63        from django.db.models.loading import load_app, find_app
    6264        from cStringIO import StringIO
    6365
    6466        try:
    6567            module = load_app(self.model_label)
     68            app = find_app(self.model_label)
    6669        except Exception, e:
    67             self.fail('Unable to load invalid model module')
     70            self.fail('Unable to load invalid application %s: %s' % (self.model_label, e))
    6871
    6972        # Make sure sys.stdout is not a tty so that we get errors without
    7073        # coloring attached (makes matching the results easier). We restore
     
    7275        orig_stdout = sys.stdout
    7376        s = StringIO()
    7477        sys.stdout = s
    75         count = get_validation_errors(s, module)
     78        count = get_validation_errors(s, app)
    7679        sys.stdout = orig_stdout
    7780        s.seek(0)
    7881        error_log = s.read()
     
    133136                    print "Importing model %s" % model_name
    134137                mod = load_app(model_label)
    135138                if mod:
    136                     if model_label not in settings.INSTALLED_APPS:
     139                    if model_label not in get_installed_app_paths():
    137140                        settings.INSTALLED_APPS.append(model_label)
    138141        except Exception, e:
    139142            sys.stderr.write("Error while importing %s:" % model_name + ''.join(traceback.format_exception(*sys.exc_info())[1:]))
Back to Top