Ticket #3591: app_labels.12.diff

File app_labels.12.diff, 37.5 KB (added by George Sakkis, 16 years ago)

Patch updated to expose verbose_name in admin; fixed bug in auth; should apply cleanly to r9498

  • django/conf/__init__.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/conf/__init__.py
    a b  
    108108        # of all those apps.
    109109        new_installed_apps = []
    110110        for app in self.INSTALLED_APPS:
    111             if app.endswith('.*'):
     111            if not isinstance(app, basestring) or not app.endswith('.*'):
     112                new_installed_apps.append(app)
     113            else:
    112114                appdir = os.path.dirname(__import__(app[:-2], {}, {}, ['']).__file__)
    113115                app_subdirs = os.listdir(appdir)
    114116                app_subdirs.sort()
    115117                for d in app_subdirs:
    116118                    if d.isalpha() and os.path.isdir(os.path.join(appdir, d)):
    117119                        new_installed_apps.append('%s.%s' % (app[:-2], d))
    118             else:
    119                 new_installed_apps.append(app)
    120120        self.INSTALLED_APPS = new_installed_apps
    121121
    122122        if hasattr(time, 'tzset'):
     
    151151
    152152settings = LazySettings()
    153153
     154class app(object):
     155    """Configuration directive for specifying an app."""
     156    def __init__(self, path, app_label=None, verbose_name=None):
     157        self.path = path
     158        # if name isn't specified, get the last part of the Python dotted path
     159        self.label = app_label or path.split('.')[-1]
     160        self.verbose_name = verbose_name or self.label
     161        self.app_module = None    # will be filled in by loading.py
     162        self.models_module = None # will be filled in by loading.py
     163
     164    def __repr__(self):
     165        return "<app: %s>" % self.path
     166
     167def get_installed_app_paths():
     168    "Return the paths of all entries in settings.INSTALLED_APPS."
     169    rv = []
     170    for a in settings.INSTALLED_APPS:
     171        if isinstance(a, basestring):
     172            rv.append(a)
     173        else:
     174            rv.append(a.path)
     175    return rv
  • django/contrib/admin/__init__.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/contrib/admin/__init__.py
    a b  
    99    may want.
    1010    """
    1111    import imp
    12     from django.conf import settings
     12    from django.conf import settings, get_installed_app_paths
    1313
    14     for app in settings.INSTALLED_APPS:
     14    for app in get_installed_app_paths():
    1515        # For each app, we need to look for an admin.py inside that app's
    1616        # package. We can't use os.path here -- recall that modules may be
    1717        # imported different ways (think zip files) -- so we need to get
  • django/contrib/admin/options.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/contrib/admin/options.py
    a b  
    88from django.contrib.admin.util import quote, unquote, flatten_fieldsets, get_deleted_objects
    99from django.core.exceptions import PermissionDenied
    1010from django.db import models, transaction
     11from django.db.models.loading import get_app
    1112from django.http import Http404, HttpResponse, HttpResponseRedirect
    1213from django.shortcuts import get_object_or_404, render_to_response
    1314from django.utils.html import escape
     
    533534            'inline_admin_formsets': inline_admin_formsets,
    534535            'errors': helpers.AdminErrorList(form, formsets),
    535536            'root_path': self.admin_site.root_path,
    536             'app_label': opts.app_label,
     537            'app_label': get_app(opts.app_label).verbose_name,
    537538        }
    538539        context.update(extra_context or {})
    539540        return self.render_change_form(request, context, add=True)
     
    612613            'inline_admin_formsets': inline_admin_formsets,
    613614            'errors': helpers.AdminErrorList(form, formsets),
    614615            'root_path': self.admin_site.root_path,
    615             'app_label': opts.app_label,
     616            'app_label': get_app(opts.app_label).verbose_name,
    616617        }
    617618        context.update(extra_context or {})
    618619        return self.render_change_form(request, context, change=True, obj=obj)
     
    644645            'cl': cl,
    645646            'has_add_permission': self.has_add_permission(request),
    646647            'root_path': self.admin_site.root_path,
    647             'app_label': app_label,
     648            'app_label': get_app(app_label).verbose_name,
    648649        }
    649650        context.update(extra_context or {})
    650651        return render_to_response(self.change_list_template or [
     
    699700            "perms_lacking": perms_needed,
    700701            "opts": opts,
    701702            "root_path": self.admin_site.root_path,
    702             "app_label": app_label,
     703            "app_label": get_app(app_label).verbose_name,
    703704        }
    704705        context.update(extra_context or {})
    705706        return render_to_response(self.delete_confirmation_template or [
     
    726727            'module_name': capfirst(force_unicode(opts.verbose_name_plural)),
    727728            'object': obj,
    728729            'root_path': self.admin_site.root_path,
    729             'app_label': app_label,
     730            'app_label': get_app(app_label).verbose_name,
    730731        }
    731732        context.update(extra_context or {})
    732733        return render_to_response(self.object_history_template or [
  • django/contrib/admin/sites.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/contrib/admin/sites.py
    a b  
    44from django.contrib.admin import ModelAdmin
    55from django.contrib.auth import authenticate, login
    66from django.db.models.base import ModelBase
     7from django.db.models.loading import get_app
    78from django.core.exceptions import ImproperlyConfigured
    89from django.shortcuts import render_to_response
    910from django.utils.safestring import mark_safe
     
    294295                        app_dict[app_label]['models'].append(model_dict)
    295296                    else:
    296297                        app_dict[app_label] = {
    297                             'name': app_label.title(),
     298                            'name': get_app(app_label).verbose_name,
    298299                            'app_url': app_label + '/',
    299300                            'has_module_perms': has_module_perms,
    300301                            'models': [model_dict],
     
    359360                            # something to display, add in the necessary meta
    360361                            # information.
    361362                            app_dict = {
    362                                 'name': app_label.title(),
     363                                'name': get_app(app_label).verbose_name,
    363364                                'app_url': '',
    364365                                'has_module_perms': has_module_perms,
    365366                                'models': [model_dict],
     
    369370        # Sort the models alphabetically within each app.
    370371        app_dict['models'].sort(lambda x, y: cmp(x['name'], y['name']))
    371372        context = {
    372             'title': _('%s administration') % capfirst(app_label),
     373            'title': _('%s administration') % get_app(app_label).verbose_name,
    373374            'app_list': [app_dict],
    374375            'root_path': self.root_path,
    375376        }
  • django/contrib/auth/management/__init__.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/contrib/auth/management/__init__.py
    a b  
    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/contrib/comments/__init__.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/contrib/comments/__init__.py
    a b  
    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
    44
     
    1111    """
    1212    # Make sure the app's in INSTALLED_APPS
    1313    comments_app = get_comment_app_name()
    14     if comments_app not in settings.INSTALLED_APPS:
     14    if comments_app not in get_installed_app_paths():
    1515        raise ImproperlyConfigured("The COMMENTS_APP (%r) "\
    1616                                   "must be in INSTALLED_APPS" % settings.COMMENTS_APP)
    1717
  • django/contrib/contenttypes/management.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/contrib/contenttypes/management.py
    a b  
    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/sites/management.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/contrib/sites/management.py
    a b  
    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/core/management/__init__.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/core/management/__init__.py
    a b  
    9696
    9797        # Find the installed apps
    9898        try:
    99             from django.conf import settings
    100             apps = settings.INSTALLED_APPS
     99            from django.conf import settings, get_installed_app_paths
     100            apps = get_installed_app_paths()
    101101        except (AttributeError, EnvironmentError, ImportError):
    102102            apps = []
    103103
  • django/core/management/commands/flush.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/core/management/commands/flush.py
    a b  
     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 optparse import make_option
     
    2122
    2223        # Import the 'management' module within each installed app, to register
    2324        # dispatcher events.
    24         for app_name in settings.INSTALLED_APPS:
     25        for app_name in get_installed_app_paths():
    2526            try:
    2627                __import__(app_name + '.management', {}, {}, [''])
    2728            except ImportError:
  • django/core/management/commands/loaddata.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/core/management/commands/loaddata.py
    a b  
    5151            transaction.enter_transaction_management()
    5252            transaction.managed(True)
    5353
    54         app_fixtures = [os.path.join(os.path.dirname(app.__file__), 'fixtures') for app in get_apps()]
     54        app_fixtures = [os.path.join(os.path.dirname(app.app_module.__file__), 'fixtures') for app in get_apps() if app.app_module]
    5555        for fixture_label in fixture_labels:
    5656            parts = fixture_label.split('.')
    5757            if len(parts) == 1:
  • django/core/management/commands/syncdb.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/core/management/commands/syncdb.py
    a b  
     1from django.conf import get_installed_app_paths
    12from django.core.management.base import NoArgsCommand
    23from django.core.management.color import no_style
    34from optparse import make_option
     
    2829
    2930        # Import the 'management' module within each installed app, to register
    3031        # dispatcher events.
    31         for app_name in settings.INSTALLED_APPS:
     32        for app_name in get_installed_app_paths():
    3233            try:
    3334                __import__(app_name + '.management', {}, {}, [''])
    3435            except ImportError, exc:
     
    5556
    5657        # Create the tables for each model
    5758        for app in models.get_apps():
    58             app_name = app.__name__.split('.')[-2]
     59            app_name = app.label
    5960            model_list = models.get_models(app)
    6061            for model in model_list:
    6162                # Create the model's database table, if it doesn't already exist.
     
    8081        # Create the m2m tables. This must be done after all tables have been created
    8182        # to ensure that all referred tables will exist.
    8283        for app in models.get_apps():
    83             app_name = app.__name__.split('.')[-2]
     84            app_name = app.label
    8485            model_list = models.get_models(app)
    8586            for model in model_list:
    8687                if model in created_models:
     
    103104        # Install custom SQL for the app (but only if this
    104105        # is a model we've just created)
    105106        for app in models.get_apps():
    106             app_name = app.__name__.split('.')[-2]
     107            app_name = app.label
    107108            for model in models.get_models(app):
    108109                if model in created_models:
    109110                    custom_sql = custom_sql_for_model(model, self.style)
     
    127128                            print "No custom SQL for %s.%s model" % (app_name, model._meta.object_name)
    128129        # Install SQL indicies for all newly created models
    129130        for app in models.get_apps():
    130             app_name = app.__name__.split('.')[-2]
     131            app_name = app.label
    131132            for model in models.get_models(app):
    132133                if model in created_models:
    133134                    index_sql = connection.creation.sql_indexes_for_model(model, self.style)
  • django/core/management/sql.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/core/management/sql.py
    a b  
    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/db/models/__init__.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/db/models/__init__.py
    a b  
    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.manager import Manager
    77from django.db.models.base import Model
  • django/db/models/base.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/db/models/base.py
    a b  
    1616from django.db.models.options import Options
    1717from django.db import connection, transaction, DatabaseError
    1818from django.db.models import signals
    19 from django.db.models.loading import register_models, get_model
     19from django.db.models.loading import register_models, get_model, get_app_label
    2020from django.utils.functional import curry
    2121from django.utils.encoding import smart_str, force_unicode, smart_unicode
    2222from django.conf import settings
     
    6969
    7070        if getattr(new_class, '_default_manager', None):
    7171            new_class._default_manager = None
     72        if getattr(new_class._meta, 'app_label', None) is None:
     73            # Figure out the app_label.
     74            new_class._meta.app_label = get_app_label(new_class)
    7275
    7376        # Bail out early if we have already created this class.
    7477        m = get_model(new_class._meta.app_label, name, False)
  • django/db/models/loading.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/db/models/loading.py
    a b  
    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
    66
    77import sys
    8 import os
     8import os, os.path
    99import threading
    1010
    1111__all__ = ('get_apps', 'get_app', 'get_models', 'get_model', 'register_models',
    12         'load_app', 'app_cache_ready')
     12        'load_app', 'app_cache_ready', 'find_app')
    1313
    1414class AppCache(object):
    1515    """
     
    2828        # Mapping of app_labels to errors raised when trying to import the app.
    2929        app_errors = {},
    3030
     31
     32        # Mapping of app_labels to app instances.
     33        app_map = {},
     34
     35        # Mapping of app module names to app instances.
     36        mod_map = {},
     37
     38        # List of app instances.
     39        app_instances = [],
     40
    3141        # -- Everything below here is only used when populating the cache --
    3242        loaded = False,
    3343        handled = {},
     
    5161        try:
    5262            if self.loaded:
    5363                return
    54             for app_name in settings.INSTALLED_APPS:
     64            # We first loop through, setting up the app instances and
     65            # the relevant maps so that we can find the instances by app_label
     66            # or app module name. These need to be ready because we need to be
     67            # able to get the app_label e.g. for applying to model classes.
     68            # If a model class is loaded indirectly without being in an
     69            # installed app, the app_label used will be what it is now - the
     70            # last part of the app module name.
     71            # Note that app_map and mod_map will contain entries even
     72            # when an app cannot be loaded by load_app.
     73            for app_entry in settings.INSTALLED_APPS:
     74                if isinstance(app_entry, basestring):
     75                    the_app = app(app_entry)
     76                else:
     77                    the_app = app_entry
     78                self.app_map[the_app.label] = the_app
     79                self.mod_map[the_app.path] = the_app
     80
     81            for app_entry in settings.INSTALLED_APPS:
     82                if isinstance(app_entry, basestring):
     83                    the_app = self.mod_map[app_entry]
     84                else:
     85                    the_app = app_entry
     86                app_name = the_app.path
    5587                if app_name in self.handled:
    5688                    continue
    57                 self.load_app(app_name, True)
     89                try:
     90                    self.load_app(app_name, True)
     91                    self.app_instances.append(the_app)
     92                except Exception, e:
     93                    # Problem importing the app
     94                    self.app_errors[app_name] = e
    5895            if not self.nesting_level:
    5996                for app_name in self.postponed:
     97                    the_app = self.mod_map[app_name]
    6098                    self.load_app(app_name)
     99                    self.app_instances.append(the_app)                   
    61100                self.loaded = True
    62101        finally:
    63102            self.write_lock.release()
     
    71110        self.nesting_level += 1
    72111        mod = __import__(app_name, {}, {}, ['models'])
    73112        self.nesting_level -= 1
     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
    74123        if not hasattr(mod, 'models'):
    75124            if can_postpone:
    76125                # Either the app has no models, or the package is still being
     
    78127                # We will check again once all the recursion has finished (in
    79128                # populate).
    80129                self.postponed.append(app_name)
    81             return None
    82         if mod.models not in self.app_store:
    83             self.app_store[mod.models] = len(self.app_store)
    84         return mod.models
     130            rv = None
     131        else:
     132            rv = mod.models
     133            if rv not in self.app_store:
     134                self.app_store[rv] = len(self.app_store)
     135        the_app.models_module = rv
     136        return rv
    85137
    86138    def app_cache_ready(self):
    87139        """
     
    101153        # list page, for example.
    102154        apps = [(v, k) for k, v in self.app_store.items()]
    103155        apps.sort()
    104         return [elt[1] for elt in apps]
     156        #return [elt[1] for elt in apps]
     157        return self.app_instances
     158
     159    def get_app_label(self, model_class):
     160        "Returns the app label to be used for a model class."
     161        key = model_class.__module__
     162        i = key.rfind('.')
     163        assert i > 0, "Model class must be defined in a package sub-module"
     164        key = key[:i]
     165        if key in self.mod_map:
     166            rv = self.mod_map[key].label
     167        else:
     168            i = key.rfind('.')
     169            if i < 0:
     170                rv = key
     171            else:
     172                rv = key[i + 1:]
     173        return rv
     174   
     175    def find_app(self, app_path):
     176        "Find an app instance, given the application path."
     177        self._populate()
     178        return self.mod_map[app_path]
    105179
    106180    def get_app(self, app_label, emptyOK=False):
    107181        """
    108         Returns the module containing the models for the given app_label. If
     182        Returns the app instance for the given app_label. If
    109183        the app has no models in it and 'emptyOK' is True, returns None.
    110184        """
    111185        self._populate()
    112         self.write_lock.acquire()
    113         try:
    114             for app_name in settings.INSTALLED_APPS:
    115                 if app_label == app_name.split('.')[-1]:
    116                     mod = self.load_app(app_name, False)
    117                     if mod is None:
    118                         if emptyOK:
    119                             return None
    120                     else:
    121                         return mod
    122             raise ImproperlyConfigured, "App with label %s could not be found" % app_label
    123         finally:
    124             self.write_lock.release()
     186        if app_label not in self.app_map:
     187            rv = None
     188        else:
     189            rv = self.app_map[app_label]
     190        if emptyOK or rv is not None:
     191            return rv
     192        raise ImproperlyConfigured, "App with label %s could not be found" % app_label
    125193
    126194    def get_app_errors(self):
    127195        "Returns the map of known problems with the INSTALLED_APPS."
    128196        self._populate()
    129197        return self.app_errors
    130198
    131     def get_models(self, app_mod=None):
     199    def get_models(self, the_app=None):
    132200        """
    133         Given a module containing models, returns a list of the models.
     201        Given an app instance, returns a list of its models.
    134202        Otherwise returns a list of all installed models.
    135203        """
    136204        self._populate()
    137         if app_mod:
    138             return self.app_models.get(app_mod.__name__.split('.')[-2], SortedDict()).values()
     205        if the_app:
     206            return self.app_models.get(the_app.label, SortedDict()).values()
    139207        else:
    140208            model_list = []
    141             for app_entry in self.app_models.itervalues():
    142                 model_list.extend(app_entry.values())
     209            for the_app in self.app_instances:
     210                model_list.extend(get_models(the_app))
    143211            return model_list
    144212
    145213    def get_model(self, app_label, model_name, seed_cache=True):
     
    187255register_models = cache.register_models
    188256load_app = cache.load_app
    189257app_cache_ready = cache.app_cache_ready
     258find_app = cache.find_app
     259get_app_label = cache.get_app_label
  • django/db/models/options.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/db/models/options.py
    a b  
    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
     
    5454        from django.db.backends.util import truncate_name
    5555
    5656        cls._meta = self
    57         self.installed = re.sub('\.models$', '', cls.__module__) in settings.INSTALLED_APPS
     57        self.installed = re.sub('\.models$', '', cls.__module__) in get_installed_app_paths()
    5858        # First, construct the default values for these options.
    5959        self.object_name = cls.__name__
    6060        self.module_name = self.object_name.lower()
  • django/template/loaders/app_directories.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/template/loaders/app_directories.py
    a b  
    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
     
    1414# At compile time, cache the directories to search.
    1515fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
    1616app_template_dirs = []
    17 for app in settings.INSTALLED_APPS:
     17for app in get_installed_app_paths():
    1818    i = app.rfind('.')
    1919    if i == -1:
    2020        m, a = app, None
  • django/template/loaders/eggs.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/template/loaders/eggs.py
    a b  
    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:
  • django/templatetags/__init__.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/templatetags/__init__.py
    a b  
    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/test/client.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/test/client.py
    a b  
    77except ImportError:
    88    from StringIO import StringIO
    99
    10 from django.conf import settings
     10from django.conf import settings, get_installed_app_paths
    1111from django.contrib.auth import authenticate, login
    1212from django.core.handlers.base import BaseHandler
    1313from django.core.handlers.wsgi import WSGIRequest
     
    171171        """
    172172        Obtains the current session variables.
    173173        """
    174         if 'django.contrib.sessions' in settings.INSTALLED_APPS:
     174        if 'django.contrib.sessions' in get_installed_app_paths():
    175175            engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
    176176            cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None)
    177177            if cookie:
     
    373373        """
    374374        user = authenticate(**credentials)
    375375        if user and user.is_active \
    376                 and 'django.contrib.sessions' in settings.INSTALLED_APPS:
     376                and 'django.contrib.sessions' in get_installed_app_paths():
    377377            engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
    378378
    379379            # Create a fake request to store login details.
  • django/test/simple.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/test/simple.py
    a b  
    6363            suite.addTest(test_module.suite())
    6464        else:
    6565            suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(test_module))
    66             try:           
     66            try:
    6767                suite.addTest(doctest.DocTestSuite(test_module,
    6868                                                   checker=doctestOutputChecker,
    6969                                                   runner=DocTestRunner))
     
    129129                suite.addTest(build_test(label))
    130130            else:
    131131                app = get_app(label)
    132                 suite.addTest(build_suite(app))
     132                mod = app.models_module
     133                if mod:
     134                  suite.addTest(build_suite(mod))
    133135    else:
    134136        for app in get_apps():
    135             suite.addTest(build_suite(app))
     137            mod = app.models_module
     138            if mod:
     139                suite.addTest(build_suite(mod))
    136140   
    137141    for test in extra_tests:
    138142        suite.addTest(test)
  • django/utils/translation/trans_real.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/utils/translation/trans_real.py
    a b  
    114114    if t is not None:
    115115        return t
    116116
    117     from django.conf import settings
     117    from django.conf import settings, get_installed_app_paths
    118118
    119119    # set up the right translation class
    120120    klass = DjangoTranslation
     
    175175        if projectpath and os.path.isdir(projectpath):
    176176            res = _merge(projectpath)
    177177
    178         for appname in settings.INSTALLED_APPS:
     178        for appname in get_installed_app_paths():
    179179            p = appname.rfind('.')
    180180            if p >= 0:
    181181                app = getattr(__import__(appname[:p], {}, {}, [appname[p+1:]]), appname[p+1:])
  • django/views/i18n.py

    diff -r 70f49cf7534d -r 2a82e03ad70a django/views/i18n.py
    a b  
    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
     
    121121        packages = ['django.conf']
    122122    if type(packages) in (str, unicode):
    123123        packages = packages.split('+')
    124     packages = [p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS]
     124    packages = [p for p in packages if p == 'django.conf' or p in get_installed_app_paths()]
    125125    default_locale = to_locale(settings.LANGUAGE_CODE)
    126126    locale = to_locale(get_language())
    127127    t = {}
  • tests/regressiontests/admin_scripts/tests.py

    diff -r 70f49cf7534d -r 2a82e03ad70a tests/regressiontests/admin_scripts/tests.py
    a b  
    969969        args = ['app_command', 'auth']
    970970        out, err = self.run_manage(args)
    971971        self.assertNoOutput(err)
    972         self.assertOutput(out, "EXECUTE:AppCommand app=<module 'django.contrib.auth.models'")
    973         self.assertOutput(out, os.sep.join(['django','contrib','auth','models.py']))
    974         self.assertOutput(out, "'>, options=[('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]")
     972        self.assertOutput(out, "EXECUTE:AppCommand app=<app: django.contrib.auth>")
     973        #self.assertOutput(out, os.sep.join(['django','contrib','auth','models.py']))
     974        self.assertOutput(out, ">, options=[('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]")
    975975
    976976    def test_app_command_no_apps(self):
    977977        "User AppCommands raise an error when no app name is provided"
     
    984984        args = ['app_command','auth','contenttypes']
    985985        out, err = self.run_manage(args)
    986986        self.assertNoOutput(err)
    987         self.assertOutput(out, "EXECUTE:AppCommand app=<module 'django.contrib.auth.models'")
    988         self.assertOutput(out, os.sep.join(['django','contrib','auth','models.py']))
    989         self.assertOutput(out, "'>, options=[('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]")
    990         self.assertOutput(out, "EXECUTE:AppCommand app=<module 'django.contrib.contenttypes.models'")
    991         self.assertOutput(out, os.sep.join(['django','contrib','contenttypes','models.py']))
    992         self.assertOutput(out, "'>, options=[('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]")
     987        self.assertOutput(out, "EXECUTE:AppCommand app=<app: django.contrib.auth>")
     988        #self.assertOutput(out, os.sep.join(['django','contrib','auth','models.py']))
     989        self.assertOutput(out, ">, options=[('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]")
     990        self.assertOutput(out, "EXECUTE:AppCommand app=<app: django.contrib.contenttypes>")
     991        #self.assertOutput(out, os.sep.join(['django','contrib','contenttypes','models.py']))
     992        self.assertOutput(out, ">, options=[('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', '1')]")
    993993
    994994    def test_app_command_invalid_appname(self):
    995995        "User AppCommands can execute when a single app name is provided"
  • tests/runtests.py

    diff -r 70f49cf7534d -r 2a82e03ad70a tests/runtests.py
    a b  
    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()
     
    129132                    print "Importing model %s" % model_name
    130133                mod = load_app(model_label)
    131134                if mod:
    132                     if model_label not in settings.INSTALLED_APPS:
     135                    if model_label not in get_installed_app_paths():
    133136                        settings.INSTALLED_APPS.append(model_label)
    134137        except Exception, e:
    135138            sys.stderr.write("Error while importing %s:" % model_name + ''.join(traceback.format_exception(*sys.exc_info())[1:]))
Back to Top