Beispiel #1
0
def setup(verbosity, test_labels):
    from django.conf import settings
    state = {
        'INSTALLED_APPS': settings.INSTALLED_APPS,
        'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""),
        'TEMPLATE_DIRS': settings.TEMPLATE_DIRS,
        'USE_I18N': settings.USE_I18N,
        'LOGIN_URL': settings.LOGIN_URL,
        'LANGUAGE_CODE': settings.LANGUAGE_CODE,
        'MIDDLEWARE_CLASSES': settings.MIDDLEWARE_CLASSES,
        'STATIC_URL': settings.STATIC_URL,
        'STATIC_ROOT': settings.STATIC_ROOT,
    }

    # Redirect some settings for the duration of these tests.
    settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
    settings.ROOT_URLCONF = 'urls'
    settings.STATIC_URL = '/static/'
    settings.STATIC_ROOT = os.path.join(TEMP_DIR, 'static')
    settings.TEMPLATE_DIRS = (os.path.join(RUNTESTS_DIR, TEST_TEMPLATE_DIR),)
    settings.USE_I18N = True
    settings.LANGUAGE_CODE = 'en'
    settings.MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.common.CommonMiddleware',
    )
    settings.SITE_ID = 1
    # For testing comment-utils, we require the MANAGERS attribute
    # to be set, so that a test email is sent out which we catch
    # in our tests.
    settings.MANAGERS = ("*****@*****.**",)

    # Load all the ALWAYS_INSTALLED_APPS.
    # (This import statement is intentionally delayed until after we
    # access settings because of the USE_I18N dependency.)

    django.setup()
    from django.db.models.loading import get_apps, load_app
    get_apps()

    # Load all the test model apps.
    test_labels_set = set([label.split('.')[0] for label in test_labels])
    test_modules = get_test_modules()

    for module_name in test_modules:
        module_label = module_name
        # if the module was named on the command line, or
        # no modules were named (i.e., run all), import
        # this module and add it to the list to test.
        if not test_labels or module_name in test_labels_set:
            if verbosity >= 2:
                print "Importing application %s" % module_name
            mod = load_app(module_label)
            if mod:
                if module_label not in settings.INSTALLED_APPS:
                    settings.INSTALLED_APPS.append(module_label)

    return state
def django_tests(verbosity, interactive, failfast, test_labels):
    from django.conf import settings

    old_installed_apps = settings.INSTALLED_APPS
    old_root_urlconf = getattr(settings, "ROOT_URLCONF", "")
    old_template_dirs = settings.TEMPLATE_DIRS
    old_use_i18n = settings.USE_I18N
    old_login_url = settings.LOGIN_URL
    old_language_code = settings.LANGUAGE_CODE
    old_middleware_classes = settings.MIDDLEWARE_CLASSES

    # Load all the ALWAYS_INSTALLED_APPS.
    # (This import statement is intentionally delayed until after we
    # access settings because of the USE_I18N dependency.)
    from django.db.models.loading import get_apps, load_app
    get_apps()

    # Load all the test model apps.
    for model_dir, model_name in get_test_models():
        model_label = '.'.join([model_dir, model_name])
        try:
            # if the model was named on the command line, or
            # no models were named (i.e., run all), import
            # this model and add it to the list to test.
            if not test_labels or model_name in set([label.split('.')[0] for label in test_labels]):
                if verbosity >= 1:
                    print "Importing model %s" % model_name
                mod = load_app(model_label)
                if mod:
                    if model_label not in settings.INSTALLED_APPS:
                        settings.INSTALLED_APPS.append(model_label)
        except Exception, e:
            sys.stderr.write("Error while importing %s:" % model_name + ''.join(traceback.format_exception(*sys.exc_info())[1:]))
            continue
def setup(verbosity, test_labels):
    from django.conf import settings
    state = {
        'INSTALLED_APPS': settings.INSTALLED_APPS,
        'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""),
        'TEMPLATE_DIRS': settings.TEMPLATE_DIRS,
        'USE_I18N': settings.USE_I18N,
        'LOGIN_URL': settings.LOGIN_URL,
        'LANGUAGE_CODE': settings.LANGUAGE_CODE,
        'MIDDLEWARE_CLASSES': settings.MIDDLEWARE_CLASSES,
        'STATIC_URL': settings.STATIC_URL,
        'STATIC_ROOT': settings.STATIC_ROOT,
    }

    # Redirect some settings for the duration of these tests.
    settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
    settings.ROOT_URLCONF = 'urls'
    settings.STATIC_URL = '/static/'
    settings.STATIC_ROOT = os.path.join(TEMP_DIR, 'static')
    settings.TEMPLATE_DIRS = (os.path.join(RUNTESTS_DIR, TEST_TEMPLATE_DIR), )
    settings.USE_I18N = True
    settings.LANGUAGE_CODE = 'en'
    settings.MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.common.CommonMiddleware',
    )
    settings.SITE_ID = 1
    # For testing comment-utils, we require the MANAGERS attribute
    # to be set, so that a test email is sent out which we catch
    # in our tests.
    settings.MANAGERS = ("*****@*****.**", )

    # Load all the ALWAYS_INSTALLED_APPS.
    # (This import statement is intentionally delayed until after we
    # access settings because of the USE_I18N dependency.)

    django.setup()
    from django.db.models.loading import get_apps, load_app
    get_apps()

    # Load all the test model apps.
    test_labels_set = set([label.split('.')[0] for label in test_labels])
    test_modules = get_test_modules()

    for module_name in test_modules:
        module_label = module_name
        # if the module was named on the command line, or
        # no modules were named (i.e., run all), import
        # this module and add it to the list to test.
        if not test_labels or module_name in test_labels_set:
            if verbosity >= 2:
                print "Importing application %s" % module_name
            mod = load_app(module_label)
            if mod:
                if module_label not in settings.INSTALLED_APPS:
                    settings.INSTALLED_APPS.append(module_label)

    return state
Beispiel #4
0
def setup(verbosity, test_labels):
    from django.conf import settings
    from django.db.models.loading import get_apps, load_app
    state = {
        'INSTALLED_APPS': settings.INSTALLED_APPS,
        'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""),
        'TEMPLATE_DIRS': settings.TEMPLATE_DIRS,
        'LANGUAGE_CODE': settings.LANGUAGE_CODE,
        'STATIC_URL': settings.STATIC_URL,
        'STATIC_ROOT': settings.STATIC_ROOT,
    }

    # Redirect some settings for the duration of these tests.
    settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
    settings.ROOT_URLCONF = 'urls'
    settings.STATIC_URL = '/static/'
    settings.STATIC_ROOT = os.path.join(TEMP_DIR, 'static')
    settings.TEMPLATE_DIRS = (os.path.join(RUNTESTS_DIR, TEST_TEMPLATE_DIR),)
    settings.LANGUAGE_CODE = 'en'
    settings.SITE_ID = 1

    if verbosity > 0:
        # Ensure any warnings captured to logging are piped through a verbose
        # logging handler.  If any -W options were passed explicitly on command
        # line, warnings are not captured, and this has no effect.
        logger = logging.getLogger('py.warnings')
        handler = logging.StreamHandler()
        logger.addHandler(handler)

    # Load all the ALWAYS_INSTALLED_APPS.
    get_apps()

    # Load all the test model apps.
    test_labels_set = set([label.split('.')[0] for label in test_labels])
    test_modules = get_test_modules()

    # If GeoDjango, then we'll want to add in the test applications
    # that are a part of its test suite.
    if geodjango(settings):
        from django.contrib.gis.tests import geo_apps
        test_modules.extend(geo_apps(runtests=True))
        settings.INSTALLED_APPS.extend(['django.contrib.gis', 'django.contrib.sitemaps'])

    for module_dir, module_name in test_modules:
        if module_dir:
            module_label = '.'.join([module_dir, module_name])
        else:
            module_label = module_name
        # if the module was named on the command line, or
        # no modules were named (i.e., run all), import
        # this module and add it to the list to test.
        if not test_labels or module_name in test_labels_set:
            if verbosity >= 2:
                print("Importing application %s" % module_name)
            mod = load_app(module_label)
            if mod:
                if module_label not in settings.INSTALLED_APPS:
                    settings.INSTALLED_APPS.append(module_label)

    return state
Beispiel #5
0
    def prepareTestRunner(self, test):
        cur_stdout = sys.stdout
        cur_stderr = sys.stderr

        sys.stdout = self.sys_stdout
        sys.stderr = self.sys_stderr

        if self.add_apps:
            for app in self.add_apps:
                if app in settings.INSTALLED_APPS:
                    continue
                mod = load_app(app)
                if mod:
                    settings.INSTALLED_APPS.append(app)

        get_apps()

        self.runner.setup_test_environment()

        if self.needs_db:
            self.old_names = self.runner.setup_databases()

        sys.stdout = cur_stdout
        sys.stderr = cur_stderr

        self.started = True
Beispiel #6
0
    def prepareTestRunner(self, test):
        cur_stdout = sys.stdout
        cur_stderr = sys.stderr

        sys.stdout = self.sys_stdout
        sys.stderr = self.sys_stderr

        if self.add_apps:
            for app in self.add_apps:
                if app in settings.INSTALLED_APPS:
                    continue
                mod = load_app(app)
                if mod:
                    settings.INSTALLED_APPS.append(app)

        get_apps()

        self.runner.setup_test_environment()

        if self.needs_db:
            self.old_names = self.runner.setup_databases()

        sys.stdout = cur_stdout
        sys.stderr = cur_stderr

        self.started = True
Beispiel #7
0
def django_tests(verbosity, interactive, failfast, test_labels):
    from django.conf import settings

    old_installed_apps = settings.INSTALLED_APPS
    old_root_urlconf = getattr(settings, "ROOT_URLCONF", "")
    old_template_dirs = settings.TEMPLATE_DIRS
    old_use_i18n = settings.USE_I18N
    old_login_url = settings.LOGIN_URL
    old_language_code = settings.LANGUAGE_CODE
    old_middleware_classes = settings.MIDDLEWARE_CLASSES

    # Redirect some settings for the duration of these tests.
    settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
    settings.ROOT_URLCONF = 'urls'
    settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__),
                                           TEST_TEMPLATE_DIR), )
    settings.USE_I18N = True
    settings.LANGUAGE_CODE = 'en'
    settings.LOGIN_URL = '/accounts/login/'
    settings.MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.common.CommonMiddleware',
    )
    settings.SITE_ID = 1
    # For testing comment-utils, we require the MANAGERS attribute
    # to be set, so that a test email is sent out which we catch
    # in our tests.
    settings.MANAGERS = ("*****@*****.**", )

    # Load all the ALWAYS_INSTALLED_APPS.
    # (This import statement is intentionally delayed until after we
    # access settings because of the USE_I18N dependency.)
    from django.db.models.loading import get_apps, load_app
    get_apps()

    # Load all the test model apps.
    for model_dir, model_name in get_test_models():
        model_label = '.'.join([model_dir, model_name])
        try:
            # if the model was named on the command line, or
            # no models were named (i.e., run all), import
            # this model and add it to the list to test.
            if not test_labels or model_name in set(
                [label.split('.')[0] for label in test_labels]):
                if verbosity >= 1:
                    print "Importing model %s" % model_name
                mod = load_app(model_label)
                if mod:
                    if model_label not in settings.INSTALLED_APPS:
                        settings.INSTALLED_APPS.append(model_label)
        except Exception, e:
            sys.stderr.write(
                "Error while importing %s:" % model_name +
                ''.join(traceback.format_exception(*sys.exc_info())[1:]))
            continue
Beispiel #8
0
def django_tests(verbosity, interactive, failfast, test_labels):
    from django.conf import settings

    old_installed_apps = settings.INSTALLED_APPS
    old_test_database_name = settings.TEST_DATABASE_NAME
    old_root_urlconf = getattr(settings, "ROOT_URLCONF", "")
    old_template_dirs = settings.TEMPLATE_DIRS
    old_use_i18n = settings.USE_I18N
    old_login_url = settings.LOGIN_URL
    old_language_code = settings.LANGUAGE_CODE
    old_middleware_classes = settings.MIDDLEWARE_CLASSES

    # Redirect some settings for the duration of these tests.
    settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
    settings.ROOT_URLCONF = "urls"
    settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), TEST_TEMPLATE_DIR),)
    settings.USE_I18N = True
    settings.LANGUAGE_CODE = "en"
    settings.LOGIN_URL = "/accounts/login/"
    settings.MIDDLEWARE_CLASSES = (
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.contrib.auth.middleware.AuthenticationMiddleware",
        "django.contrib.messages.middleware.MessageMiddleware",
        "django.middleware.common.CommonMiddleware",
    )
    settings.SITE_ID = 1
    # For testing comment-utils, we require the MANAGERS attribute
    # to be set, so that a test email is sent out which we catch
    # in our tests.
    settings.MANAGERS = ("*****@*****.**",)

    # Load all the ALWAYS_INSTALLED_APPS.
    # (This import statement is intentionally delayed until after we
    # access settings because of the USE_I18N dependency.)
    from django.db.models.loading import get_apps, load_app

    get_apps()

    # Load all the test model apps.
    for model_dir, model_name in get_test_models():
        model_label = ".".join([model_dir, model_name])
        try:
            # if the model was named on the command line, or
            # no models were named (i.e., run all), import
            # this model and add it to the list to test.
            if not test_labels or model_name in set([label.split(".")[0] for label in test_labels]):
                if verbosity >= 1:
                    print "Importing model %s" % model_name
                mod = load_app(model_label)
                if mod:
                    if model_label not in settings.INSTALLED_APPS:
                        settings.INSTALLED_APPS.append(model_label)
        except Exception, e:
            sys.stderr.write(
                "Error while importing %s:" % model_name + "".join(traceback.format_exception(*sys.exc_info())[1:])
            )
            continue
Beispiel #9
0
def setup(verbosity, test_labels):
    from django.conf import settings

    state = {
        "INSTALLED_APPS": settings.INSTALLED_APPS,
        "ROOT_URLCONF": getattr(settings, "ROOT_URLCONF", ""),
        "TEMPLATE_DIRS": settings.TEMPLATE_DIRS,
        "USE_I18N": settings.USE_I18N,
        "LOGIN_URL": settings.LOGIN_URL,
        "LANGUAGE_CODE": settings.LANGUAGE_CODE,
        "MIDDLEWARE_CLASSES": settings.MIDDLEWARE_CLASSES,
    }

    # Redirect some settings for the duration of these tests.
    settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
    settings.ROOT_URLCONF = "urls"
    settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), TEST_TEMPLATE_DIR),)
    settings.USE_I18N = True
    settings.LANGUAGE_CODE = "en"
    settings.LOGIN_URL = "/accounts/login/"
    settings.MIDDLEWARE_CLASSES = (
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.contrib.auth.middleware.AuthenticationMiddleware",
        "django.contrib.messages.middleware.MessageMiddleware",
        "django.middleware.common.CommonMiddleware",
    )
    settings.SITE_ID = 1
    # For testing comment-utils, we require the MANAGERS attribute
    # to be set, so that a test email is sent out which we catch
    # in our tests.
    settings.MANAGERS = ("*****@*****.**",)

    # Load all the ALWAYS_INSTALLED_APPS.
    # (This import statement is intentionally delayed until after we
    # access settings because of the USE_I18N dependency.)
    from django.db.models.loading import get_apps, load_app

    get_apps()

    # Load all the test model apps.
    test_labels_set = set([label.split(".")[0] for label in test_labels])
    for model_dir, model_name in get_test_models():
        model_label = ".".join([model_dir, model_name])
        # if the model was named on the command line, or
        # no models were named (i.e., run all), import
        # this model and add it to the list to test.
        if not test_labels or model_name in test_labels_set:
            if verbosity >= 2:
                print "Importing model %s" % model_name
            mod = load_app(model_label)
            if mod:
                if model_label not in settings.INSTALLED_APPS:
                    settings.INSTALLED_APPS.append(model_label)

    return state
Beispiel #10
0
def django_tests(verbosity, interactive, test_labels):
    from django.conf import settings

    import deseb
    deseb.add_aka_support()

    old_installed_apps = settings.INSTALLED_APPS
    old_test_database_name = settings.TEST_DATABASE_NAME
    old_root_urlconf = settings.ROOT_URLCONF
    old_template_dirs = settings.TEMPLATE_DIRS
    old_use_i18n = settings.USE_I18N
    old_middleware_classes = settings.MIDDLEWARE_CLASSES

    # Redirect some settings for the duration of these tests.
    settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
    settings.ROOT_URLCONF = 'urls'
    settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__),
                                           TEST_TEMPLATE_DIR), )
    settings.USE_I18N = True
    settings.MIDDLEWARE_CLASSES = (
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.middleware.common.CommonMiddleware',
    )
    if not hasattr(settings, 'SITE_ID'):
        settings.SITE_ID = 1

    # Load all the ALWAYS_INSTALLED_APPS.
    # (This import statement is intentionally delayed until after we
    # access settings because of the USE_I18N dependency.)
    from django.db.models.loading import get_apps, load_app
    get_apps()

    # Load all the test model apps.
    test_models = []
    for model_dir, model_name in get_test_models():
        model_label = '.'.join([model_dir, model_name])
        try:
            # if the model was named on the command line, or
            # no models were named (i.e., run all), import
            # this model and add it to the list to test.
            if not test_labels or model_name in set(
                [label.split('.')[0] for label in test_labels]):
                if verbosity >= 1:
                    print "Importing model %s" % model_name
                mod = load_app(model_label)
                if mod:
                    if model_label not in settings.INSTALLED_APPS:
                        settings.INSTALLED_APPS.append(model_label)
        except Exception, e:
            sys.stderr.write(
                "Error while importing %s:" % model_name +
                ''.join(traceback.format_exception(*sys.exc_info())[1:]))
            continue
Beispiel #11
0
def django_tests(verbosity, interactive, test_labels):
    from django.conf import settings

    import deseb

    deseb.add_aka_support()

    old_installed_apps = settings.INSTALLED_APPS
    old_test_database_name = settings.TEST_DATABASE_NAME
    old_root_urlconf = settings.ROOT_URLCONF
    old_template_dirs = settings.TEMPLATE_DIRS
    old_use_i18n = settings.USE_I18N
    old_middleware_classes = settings.MIDDLEWARE_CLASSES

    # Redirect some settings for the duration of these tests.
    settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
    settings.ROOT_URLCONF = "urls"
    settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), TEST_TEMPLATE_DIR),)
    settings.USE_I18N = True
    settings.MIDDLEWARE_CLASSES = (
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.contrib.auth.middleware.AuthenticationMiddleware",
        "django.middleware.common.CommonMiddleware",
    )
    if not hasattr(settings, "SITE_ID"):
        settings.SITE_ID = 1

    # Load all the ALWAYS_INSTALLED_APPS.
    # (This import statement is intentionally delayed until after we
    # access settings because of the USE_I18N dependency.)
    from django.db.models.loading import get_apps, load_app

    get_apps()

    # Load all the test model apps.
    test_models = []
    for model_dir, model_name in get_test_models():
        model_label = ".".join([model_dir, model_name])
        try:
            # if the model was named on the command line, or
            # no models were named (i.e., run all), import
            # this model and add it to the list to test.
            if not test_labels or model_name in set([label.split(".")[0] for label in test_labels]):
                if verbosity >= 1:
                    print "Importing model %s" % model_name
                mod = load_app(model_label)
                if mod:
                    if model_label not in settings.INSTALLED_APPS:
                        settings.INSTALLED_APPS.append(model_label)
        except Exception, e:
            sys.stderr.write(
                "Error while importing %s:" % model_name + "".join(traceback.format_exception(*sys.exc_info())[1:])
            )
            continue
Beispiel #12
0
 def on_each_app(self, methname, *args):
     "See :func:`dd.on_each_app`."
     from django.db.models import loading
     for mod in loading.get_apps():
         meth = getattr(mod, methname, None)
         if meth is not None:
             meth(self, *args)
Beispiel #13
0
    def _import_objects(self, modules):
        from django.db.models.loading import get_models, get_apps
        loaded_models = get_models()
        # Set up a dictionary to serve as the environment for the shell, so
        # that tab completion works on objects that are imported at runtime.
        # See ticket 5082.
        imported_objects = {}

        for app_mod in get_apps():
            app_models = get_models(app_mod)
            if not app_models:
                continue
            model_labels = ", ".join([model.__name__ for model in app_models])
            print self.style.SQL_COLTYPE(
                "From '%s' autoload: %s" %
                (app_mod.__name__.split('.')[-2], model_labels))
            for model in app_models:
                try:
                    imported_objects[model.__name__] = getattr(
                        __import__(app_mod.__name__, {}, {}, model.__name__),
                        model.__name__)
                except AttributeError, e:
                    print self.style.ERROR_OUTPUT(
                        "Failed to import '%s' from '%s' reason: %s" %
                        (model.__name__, app_mod.__name__.split('.')[-2],
                         str(e)))
                    continue
def filter_model_fields(app_labels=None, model_fields=None):
    """
    Collect a filtered and sorted list of model fields.

    >>> from django.db import models
    >>> fields = filter_model_fields(
    ...     app_labels = ("auth",), model_fields = (models.CharField,)
    ... )
    >>> field2dot_name(fields[0])
    'auth.Group.name'
    >>> [field.get_attname() for field in fields]
    ['name', 'codename', 'name', 'email', 'first_name', 'last_name', 'password', 'username']

    :param app_labels: Filter by app labels, if None: all installed apps
    :param model_fields: List of field classes for filtering
    :return: field list, sorted by dot name representation
    """
    filtered_fields = set()
    for app in get_apps():
        for model in get_models(app):
            for field in model._meta.fields:
                if app_labels is not None:
                    if field.model._meta.app_label not in app_labels:
                        continue

                if not isinstance(field, model_fields):
                    continue

                filtered_fields.add(field)

    return sort_fields(filtered_fields)
Beispiel #15
0
 def proposed_indexes(self):
     """
     Return all indexes Django proposes & SQL for indexes
     """
     all_indexes = []
     proposed_indexes = {}
     index_sql = {}
     for app in get_apps():
         all_indexes.append(u'\n'.join(sql_indexes(app,
                                                   no_style(),connection)).encode('utf-8'))
     #Sort out all the proposed indexes by table.
     for index in all_indexes:
         indice = index.split('\n')
         for ind in indice:
             try:
                 match = index_re.search(ind)
                 name, table, field = match.groups()
                 if proposed_indexes.has_key(table):
                     proposed_indexes[table].append(field)
                 else:
                     proposed_indexes[table] = [field]
                 if index_sql.has_key(name):
                     index_sql[name].append(ind)
                 else:
                     index_sql[name] = [ind]
             except:
                 pass
     return proposed_indexes, index_sql
    def handle_noargs(self, **options):
        from django.db.models import loading
        from django.core.management import call_command

        for app in loading.get_apps():
            call_command('reset', app.__name__.split('.')[-2], interactive=False)
        call_command('syncdb')
Beispiel #17
0
    def generate_files(self):

        from lino.ui.extjs3 import UI

        # ~ UI = settings.SITE.get_ui_class
        ui = UI(make_messages=True)
        # ~ # install Lino urls under root location (`/`)
        # ~ ui = urlpatterns = ui.get_patterns()
        # ~ settings.SITE.setup()
        ui.make_linolib_messages()

        context = dict(
            header=rstgen.header,
            h1=curry(rstgen.header, 1),
            table=rstgen.table,
            doc=doc2rst,
            loading=loading,
            models=models,
            abstract=abstract,
            refto=refto,
            # ~ py2rst=rstgen.py2rst,
            full_model_name=full_model_name,
            model_overview=model_overview,
            model_referenced_from=model_referenced_from,
            model_ref=model_ref,
        )
        self.generate("index.rst.tmpl", "index.rst", **context)
        for a in loading.get_apps():
            app_label = a.__name__.split(".")[-2]
            app_models = models.get_models(a, include_auto_created=True)
            context.update(app=a, app_label=app_label, app_models=app_models)
            self.generate("app.rst.tmpl", "%s.rst" % app_label, **context)
            for model in app_models:
                context.update(model=model)
                self.generate("model.rst.tmpl", "%s.rst" % full_model_name(model), **context)
Beispiel #18
0
    def handle_noargs(self, **options):
        # XXX: (Temporary) workaround for ticket #1796: force early loading of all
        # models from installed apps. (this is fixed by now, but leaving it here
        # for people using 0.96 or older trunk (pre [5919]) versions.
        from django.db.models.loading import get_models, get_apps
        loaded_models = get_models()

        use_plain = options.get('plain', False)
        use_pythonrc = not options.get('no_pythonrc', True)

        # Set up a dictionary to serve as the environment for the shell, so
        # that tab completion works on objects that are imported at runtime.
        # See ticket 5082.
        from django.conf import settings
        imported_objects = {'settings': settings}
        for app_mod in get_apps():
            app_models = get_models(app_mod)
            if not app_models:
                continue
            model_labels = ", ".join([model.__name__ for model in app_models])
            print self.style.SQL_COLTYPE("From '%s' autoload: %s" % (app_mod.__name__.split('.')[-2], model_labels))
            for model in app_models:
                try:
                    imported_objects[model.__name__] = getattr(__import__(app_mod.__name__, {}, {}, model.__name__), model.__name__)
                except AttributeError, e:
                    print self.style.ERROR_OUTPUT("Failed to import '%s' from '%s' reason: %s" % (model.__name__, app_mod.__name__.split('.')[-2], str(e)))
                    continue
Beispiel #19
0
def runjobs(labels = [], verbose = False):
    """ Run all jobs in all applications if they match the labels """
    if len(labels) > 0:
        # Import the modules
        from django.db.models.loading import get_apps
        # Get all installed applications
        for app in get_apps():
            # Define the job module path
            job_path = '.'.join(app.__name__.split('.')[:-1])+'.jobs'
            # Try to import the module
            try:
                job_module = __import__(job_path, globals(), locals(), ['*'])
            except ImportError:
                pass
            else:
                # The module has been imported, get its elements
                for (job_name, job_class) in inspect.getmembers(job_module):
                    # Use only the classes
                    if inspect.isclass(job_class):
                        # Test the class is Job-based
                        if job_class.__base__ is Job:
                            # Check if the job class is found in labels
                            if job_class.__name__.lower() in labels:
                                # Instantiate the job object
                                job = job_class(verbose = verbose)
                                job.runjobs()
Beispiel #20
0
def add_new_model(request, model_name):
    if (model_name.lower() == model_name):
        normal_model_name = model_name.capitalize()
    else:
        normal_model_name = model_name

    app_list = get_apps()
    for app in app_list:
        for model in get_models(app):
            if model.__name__ == normal_model_name:
                form = modelform_factory(model)

                if request.method == 'POST':
                    form = form(request.POST)
                    if form.is_valid():
                        try:
                            new_obj = form.save()
                        except forms.ValidationError, error:
                            new_obj = None

                        if new_obj:
                            return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % \
                                (escape(new_obj._get_pk_val()), escape(new_obj)))

                else:
                    form = form()

                page_context = {'form': form, 'field': normal_model_name}
                return render_to_response('widgets/popup.html', page_context, context_instance=RequestContext(request))
    def handle(self, *args, **kwargs):
        if settings.DATABASES['default']['ENGINE'] != 'django.db.backends.sqlite3':
            if input('Database engine is not SQLite. Do you wish load staging data? [y/N]') != 'y':
                return

        env = kwargs.get('env')
        options = kwargs.get('options', {})

        app_module_paths = []
        for app in get_apps():
            if hasattr(app, '__path__'):
                # It's a 'models/' subpackage
                for path in app.__path__:
                    app_module_paths.append(path)
            else:
                # It's a models.py module
                app_module_paths.append(app.__file__)

        app_fixtures = [os.path.join(os.path.dirname(path), 'fixtures') for path in app_module_paths]
        app_fixtures += settings.FIXTURE_DIRS

        fixtures = []

        for app in app_fixtures:
            if os.path.exists(app):
                fixtures.extend(self.load_path(app, options, env))

        call_command('loaddata', *fixtures, **options)

        on_load_staging.send(app_fixtures)
Beispiel #22
0
def get_permission_choices():
    """
        Rather than creating permissions in the datastore which is incredibly slow (and relational)
        we just use the permission codenames, stored in a ListField.
    """

    global PERMISSIONS_LIST

    if PERMISSIONS_LIST:
        return PERMISSIONS_LIST

    from django.conf import settings

    AUTO_PERMISSIONS = getattr(settings, "AUTOGENERATED_PERMISSIONS",
                               ('add', 'change', 'delete'))

    result = getattr(settings, "MANUAL_PERMISSIONS", [])

    for app in get_apps():
        for model in get_models(app):
            for action in AUTO_PERMISSIONS:
                opts = model._meta
                result.append(
                    ('%s.%s' %
                     (opts.app_label, get_permission_codename(action, opts)),
                     'Can %s %s' % (action, opts.verbose_name_raw)))

    PERMISSIONS_LIST = sorted(result)
    return PERMISSIONS_LIST
Beispiel #23
0
def auto_patch_all():
    for app in get_apps():
        for model in get_models(app):
            try:
                patch_admin(model, skip_non_revision=True)
            except Exception as err:
                logging.warning("Can't patch admin for model %r: %s" % (model, err))
Beispiel #24
0
def get_import_objects():
    """
    Collect objects to populate the interactive session
    """
    imported_objects = {}
    loaded_model_names = set()
    for app in get_apps():
        app_name = app.__name__.split('.')[-2]
        for model in get_models(app):
            model_name = model.__name__
            if model_name in loaded_model_names:
                model_name = '_'.join((app_name, model_name))
            else:
                loaded_model_names.add(model_name)
            imported_objects[model_name] = model

    for extra_import in settings.EXTRA_SHELLPLUS_IMPORTS:
        if isinstance(extra_import, basestring):
            obj = import_object(extra_import)
            name = extra_import.split('.')[-1]
        else:
            import_path, name = extra_import
            obj = import_object(import_path)
        imported_objects[name] = obj

    return imported_objects
def filter_model_fields(app_labels=None, model_fields=None):
    """
    Collect a filtered and sorted list of model fields.

    >>> from django.db import models
    >>> fields = filter_model_fields(
    ...     app_labels = ("auth",), model_fields = (models.CharField,)
    ... )
    >>> field2dot_name(fields[0])
    'auth.Group.name'
    >>> [field.get_attname() for field in fields]
    ['name', 'codename', 'name', 'email', 'first_name', 'last_name', 'password', 'username']

    :param app_labels: Filter by app labels, if None: all installed apps
    :param model_fields: List of field classes for filtering
    :return: field list, sorted by dot name representation
    """
    filtered_fields = set()
    for app in get_apps():
        for model in get_models(app):
            for field in model._meta.fields:
                if app_labels is not None:
                    if field.model._meta.app_label not in app_labels:
                        continue

                if not isinstance(field, model_fields):
                    continue

                filtered_fields.add(field)

    return sort_fields(filtered_fields)
Beispiel #26
0
    def safe_build_suite(self, test_labels, extra_tests=None, **kwargs):
        suite = unittest.TestSuite()

        if test_labels:
            for label in test_labels:
                try:
                    if '.' in label:
                        suite.addTest(build_test(label))
                    else:
                        app = get_app(label)
                        suite.addTest(build_suite(app))
                except Exception:
                    log.warning("Could not add test for label: %s" %label)
        else:
            for app in get_apps():
                try:
                    suite.addTest(build_suite(app))
                except Exception:
                    log.warning("Could not add tests for app: %s" %app)

        if extra_tests:
            for test in extra_tests:
                suite.addTest(test)

        return reorder_suite(suite, (TestCase,))
Beispiel #27
0
def add_new_model(request, model_name):
    if (model_name.lower() == model_name):
        normal_model_name = model_name.capitalize()
    else:
        normal_model_name = model_name
    app_list = get_apps()
    for app in app_list:
        for model in get_models(app):
            if model.__name__ == normal_model_name:
                form = modelform_factory(model)
                if request.method == 'POST':
                    form = form(request.POST)
                    if form.is_valid():
                        try:
                            new_obj = form.save()
                        except forms.ValidationError as error:
                            new_obj = None
                        if new_obj:
                            return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % \
                                (escape(new_obj._get_pk_val()), escape(new_obj)))
                else:
                    form = form()
                page_context = {'form': form, 'field': normal_model_name}
                return render_to_response(
                    'browse/popup.html',
                    page_context,
                    context_instance=RequestContext(request))
Beispiel #28
0
def add_new_model(request, model_name):

    if (model_name.lower() == model_name):
            normal_model_name = model_name.capitalize()
    else:
        normal_model_name = model_name
    app_list = get_apps()
    for app in app_list:
        for model in get_models(app):
            if model.__name__ == normal_model_name:
                form = modelform_factory(model)
            
                if request.method == 'POST':
                    form = form(request.POST)
                    if form.is_valid():
                        try:
                            new_obj = form.save()
                        except forms.ValidationError as error:
                            new_obj = None
                    
                        if new_obj:
                            return HttpResponse('<script type="text/javascript">opener.location.reload();window.close();</script>')
                else:
                    form = form()
                page_context = {'form': form, 'field': normal_model_name}
                return render_to_response('popup.html', page_context, context_instance=RequestContext(request))
Beispiel #29
0
def make_namespace():
    ns = {}
    for app in get_apps():
        for model in get_models(app):
            ns[model.__name__] = model
            ns[model._meta.app_label + '_' + model._meta.object_name] = model
    return ns
Beispiel #30
0
    def generate_files(self):

        from lino.ui.extjs3 import UI
        #~ UI = settings.SITE.get_ui_class
        ui = UI(make_messages=True)
        # ~ # install Lino urls under root location (`/`)
        #~ ui = urlpatterns = ui.get_patterns()
        #~ settings.SITE.setup()
        ui.make_linolib_messages()

        context = dict(
            header=rstgen.header,
            h1=curry(rstgen.header, 1),
            table=rstgen.table,
            doc=doc2rst,
            loading=loading,
            models=models,
            abstract=abstract,
            refto=refto,
            #~ py2rst=rstgen.py2rst,
            full_model_name=full_model_name,
            model_overview=model_overview,
            model_referenced_from=model_referenced_from,
            model_ref=model_ref,
        )
        self.generate('index.rst.tmpl', 'index.rst', **context)
        for a in loading.get_apps():
            app_label = a.__name__.split('.')[-2]
            app_models = models.get_models(a, include_auto_created=True)
            context.update(app=a, app_label=app_label, app_models=app_models)
            self.generate('app.rst.tmpl', '%s.rst' % app_label, **context)
            for model in app_models:
                context.update(model=model, )
                self.generate('model.rst.tmpl',
                              '%s.rst' % full_model_name(model), **context)
Beispiel #31
0
def get_permission_choices():
    """
        Rather than creating permissions in the datastore which is incredibly slow (and relational)
        we just use the permission codenames, stored in a ListField.
    """

    global PERMISSIONS_LIST

    if PERMISSIONS_LIST:
        return PERMISSIONS_LIST

    from django.conf import settings

    AUTO_PERMISSIONS = getattr(settings, "AUTOGENERATED_PERMISSIONS", ('add', 'change', 'delete'))

    result = getattr(settings, "MANUAL_PERMISSIONS", [])

    for app in get_apps():
        for model in get_models(app):
            for action in AUTO_PERMISSIONS:
                opts = model._meta
                result.append((get_permission_codename(action, opts), 'Can %s %s' % (action, opts.verbose_name_raw)))

    PERMISSIONS_LIST = sorted(result)
    return PERMISSIONS_LIST
Beispiel #32
0
def make_namespace():
    ns = {}
    for app in get_apps():
        for model in get_models(app):
            ns[model.__name__] = model
            ns[model._meta.app_label + '_' + model._meta.object_name] = model
    return ns
Beispiel #33
0
    def _import_objects(self, modules):
        from django.db.models.loading import get_models, get_apps

        loaded_models = get_models()
        # Set up a dictionary to serve as the environment for the shell, so
        # that tab completion works on objects that are imported at runtime.
        # See ticket 5082.
        imported_objects = {}

        for app_mod in get_apps():
            app_models = get_models(app_mod)
            if not app_models:
                continue
            model_labels = ", ".join([model.__name__ for model in app_models])
            print self.style.SQL_COLTYPE("From '%s' autoload: %s" % (app_mod.__name__.split(".")[-2], model_labels))
            for model in app_models:
                try:
                    imported_objects[model.__name__] = getattr(
                        __import__(app_mod.__name__, {}, {}, model.__name__), model.__name__
                    )
                except AttributeError, e:
                    print self.style.ERROR_OUTPUT(
                        "Failed to import '%s' from '%s' reason: %s"
                        % (model.__name__, app_mod.__name__.split(".")[-2], str(e))
                    )
                    continue
Beispiel #34
0
def bisect_tests(bisection_label, options, test_labels):
    state = setup(int(options.verbosity), test_labels)

    if not test_labels:
        # Get the full list of test labels to use for bisection
        from django.db.models.loading import get_apps
        test_labels = [app.__name__.split('.')[-2] for app in get_apps()]

    print('***** Bisecting test suite: %s' % ' '.join(test_labels))

    # Make sure the bisection point isn't in the test list
    # Also remove tests that need to be run in specific combinations
    for label in [bisection_label, 'model_inheritance_same_model_name']:
        try:
            test_labels.remove(label)
        except ValueError:
            pass

    subprocess_args = [
        sys.executable, __file__, '--settings=%s' % options.settings]
    if options.failfast:
        subprocess_args.append('--failfast')
    if options.verbosity:
        subprocess_args.append('--verbosity=%s' % options.verbosity)
    if not options.interactive:
        subprocess_args.append('--noinput')

    iteration = 1
    while len(test_labels) > 1:
        midpoint = len(test_labels)/2
        test_labels_a = test_labels[:midpoint] + [bisection_label]
        test_labels_b = test_labels[midpoint:] + [bisection_label]
        print('***** Pass %da: Running the first half of the test suite' % iteration)
        print('***** Test labels: %s' % ' '.join(test_labels_a))
        failures_a = subprocess.call(subprocess_args + test_labels_a)

        print('***** Pass %db: Running the second half of the test suite' % iteration)
        print('***** Test labels: %s' % ' '.join(test_labels_b))
        print('')
        failures_b = subprocess.call(subprocess_args + test_labels_b)

        if failures_a and not failures_b:
            print("***** Problem found in first half. Bisecting again...")
            iteration = iteration + 1
            test_labels = test_labels_a[:-1]
        elif failures_b and not failures_a:
            print("***** Problem found in second half. Bisecting again...")
            iteration = iteration + 1
            test_labels = test_labels_b[:-1]
        elif failures_a and failures_b:
            print("***** Multiple sources of failure found")
            break
        else:
            print("***** No source of failure found... try pair execution (--pair)")
            break

    if len(test_labels) == 1:
        print("***** Source of error: %s" % test_labels[0])
    teardown(state)
Beispiel #35
0
    def handle(self, *app_labels, **options):
        if options.get("list_models", False):
            print "List all installed models:"
            data = []
            for app in get_apps():
                app_name = app.__name__.split('.')[-2] # assuming -1 is 'models' and -2 is name
                models = tuple([model.__name__ for model in get_models(app)])
                if models:
                    data.append([app_name, models])
            pprint.pprint(data)
            return

        file_path = os.path.join(FIXTURE_PATH, FIXTURE_FILENAME)

        if options.get("test", False):
            if not os.path.isfile(file_path):
                print "fixture file not exist: %r" % file_path
                return

            from django.utils import simplejson
            f = codecs.open(file_path, "r", encoding="utf-8")
            data = simplejson.load(f)
            f.close()
            print "loaded %s entries from %s" % (len(data), file_path)
            return

        json_serializer = serializers.get_serializer("json")()

        objects = []
        for app_name, model_names in APP_MODEL_DATA:
            print "App: %r" % app_name
            for model_name in model_names:
                print "\tModel: %r" % model_name
                model = get_model(app_name, model_name)

                if model_name == "PageTree":
                    # Get the PageTree objects ordered by topology!
                    data = get_pagetree_objects(model)
                else:
                    data = model._default_manager.all()

                objects.extend(data)

            print " -" * 39

        if not os.path.isdir(FIXTURE_PATH):
            print "Create dir %r" % FIXTURE_PATH
            os.makedirs(FIXTURE_PATH)

        print "Serialize data and save it into %r..." % FIXTURE_FILENAME
        try:
            with codecs.open(file_path, "w", encoding="utf-8") as out:
                json_serializer.serialize(objects, indent=options['indent'], stream=out,
                    ensure_ascii=False # http://docs.djangoproject.com/en/dev/topics/serialization/#notes-for-specific-serialization-formats
                )
        except Exception, e:
            if options['traceback']:
                raise
            raise CommandError("Unable to serialize database: %s" % e)
Beispiel #36
0
def get_model(model_name):
    app_list = get_apps()
    for app in app_list:
        for model in get_models(app):
            if model.__name__ == model_name:
                return model
                
    raise Exception('Did not find the model %s' % (model_name))
def get_model(model_name):
    app_list = get_apps()
    for app in app_list:
        for model in get_models(app):
            if model.__name__ == model_name:
                return model

    raise Exception("Did not find the model %s" % model_name)
Beispiel #38
0
def run():
    for app_mod in get_apps():
        app_models = get_models(app_mod)
        for model in app_models:
            try:
                print model.__module__, model.__name__, model.objects.all().count()
            except Exception, e:
                print e
Beispiel #39
0
    def handle(self, *args, **options):
        all_indexes = []
        proposed_indexes = {}
        index_sql = {}
        for app in get_apps():
            all_indexes.append(u'\n'.join(
                sql_indexes(app, no_style(), connection)).encode('utf-8'))
        #Sort out all the proposed indexes by table.
        for index in all_indexes:
            indice = index.split('\n')
            for ind in indice:
                try:
                    match = index_re.search(ind)
                    name, table, field = match.groups()
                    if table in proposed_indexes:
                        proposed_indexes[table].append(name)
                    else:
                        proposed_indexes[table] = [name]
                    if name in index_sql:
                        index_sql[name].append(ind)
                    else:
                        index_sql[name] = [ind]
                except:
                    pass

        #Now get all the real indexes.
        indexes = {}
        cursor = connection.cursor()
        vals = cursor.execute(CURRENT_INDEX_SQL)
        sql_back = cursor.fetchall()
        for row in sql_back:
            name, table = row
            if table in indexes:
                indexes[table].append(name)
            else:
                indexes[table] = [name]

        #For all the proposed indexes, see if they exist
        #If not, tell us!
        for prop_name, prop_tables in proposed_indexes.items():
            for table in prop_tables:
                try:
                    if not table in indexes[prop_name]:
                        if not options['show']:
                            logger.info("(%s, %s) is missing", prop_name,
                                        table)
                        else:
                            for index in index_sql[table]:
                                if prop_name in index:
                                    logger.info(index)
                except KeyError:
                    if not options['show']:
                        logger.info("No Indexes for %s in original db",
                                    prop_name)
                    else:
                        for index in index_sql[table]:
                            if table in index:
                                logger.info(index)
Beispiel #40
0
def import_objects(options, style):

    class ObjectImportError(Exception):
        pass

    # XXX: (Temporary) workaround for ticket #1796: force early loading of all
    # models from installed apps. (this is fixed by now, but leaving it here
    # for people using 0.96 or older trunk (pre [5919]) versions.

    from django.db.models.loading import get_models, get_apps
    # from django.db.models.loading import get_models, get_apps
    loaded_models = get_models()  # NOQA

    from django.conf import settings
    imported_objects = {'settings': settings}

    dont_load_cli = options.get('dont_load')  # optparse will set this to [] if it doensnt exists
    dont_load_conf = getattr(settings, 'SHELL_PLUS_DONT_LOAD', [])
    dont_load = dont_load_cli + dont_load_conf
    quiet_load = options.get('quiet_load')

    model_aliases = getattr(settings, 'SHELL_PLUS_MODEL_ALIASES', {})

    for app_mod in get_apps():
        app_models = get_models(app_mod)
        if not app_models:
            continue

        app_name = app_mod.__name__.split('.')[-2]
        if app_name in dont_load:
            continue

        app_aliases = model_aliases.get(app_name, {})
        model_labels = []

        for model in app_models:
            try:
                imported_object = getattr(__import__(app_mod.__name__, {}, {}, model.__name__), model.__name__)
                model_name = model.__name__

                if "%s.%s" % (app_name, model_name) in dont_load:
                    continue

                alias = app_aliases.get(model_name, model_name)
                imported_objects[alias] = imported_object
                if model_name == alias:
                    model_labels.append(model_name)
                else:
                    model_labels.append("%s (as %s)" % (model_name, alias))

            except AttributeError as e:
                if not quiet_load:
                    print(style.ERROR("Failed to import '%s' from '%s' reason: %s" % (model.__name__, app_name, str(e))))
                continue
        if not quiet_load:
            print(style.SQL_COLTYPE("From '%s' autoload: %s" % (app_mod.__name__.split('.')[-2], ", ".join(model_labels))))

    return imported_objects
Beispiel #41
0
    def handle_noargs(self, **options):
        # XXX: (Temporary) workaround for ticket #1796: force early loading of all
        # models from installed apps. (this is fixed by now, but leaving it here
        # for people using 0.96 or older trunk (pre [5919]) versions.
        from django.db.models.loading import get_models, get_apps
        loaded_models = get_models()

        use_ipython = options.get('ipython', False)
        use_plain = options.get('plain', False)
        use_pythonrc = not options.get('no_pythonrc', True)

        if options.get("print_sql", False):
            # Code from http://gist.github.com/118990
            from django.db.backends import util
            try:
                import sqlparse
            except ImportError:
                sqlparse = None

            class PrintQueryWrapper(util.CursorDebugWrapper):
                def execute(self, sql, params=()):
                    try:
                        return self.cursor.execute(sql, params)
                    finally:
                        raw_sql = self.db.ops.last_executed_query(
                            self.cursor, sql, params)
                        if sqlparse:
                            print sqlparse.format(raw_sql, reindent=True)
                        else:
                            print raw_sql
                        print

            util.CursorDebugWrapper = PrintQueryWrapper

        # Set up a dictionary to serve as the environment for the shell, so
        # that tab completion works on objects that are imported at runtime.
        # See ticket 5082.
        from django.conf import settings
        imported_objects = {'settings': settings}
        for app_mod in get_apps():
            app_models = get_models(app_mod)
            if not app_models:
                continue
            model_labels = ", ".join([model.__name__ for model in app_models])
            print self.style.SQL_COLTYPE(
                "From '%s' autoload: %s" %
                (app_mod.__name__.split('.')[-2], model_labels))
            for model in app_models:
                try:
                    imported_objects[model.__name__] = getattr(
                        __import__(app_mod.__name__, {}, {}, model.__name__),
                        model.__name__)
                except AttributeError, e:
                    print self.style.ERROR(
                        "Failed to import '%s' from '%s' reason: %s" %
                        (model.__name__, app_mod.__name__.split('.')[-2],
                         str(e)))
                    continue
Beispiel #42
0
def get_model_form(model_name):
    app_list = get_apps()
    for app in app_list:
        for model in get_models(app):
            if model.__name__ == model_name: 
                form = modelform_factory(model)
                return form

    raise Exception('Did not find the model %s' % model_name)
Beispiel #43
0
def get_model_form(model_name):
    app_list = get_apps()
    for app in app_list:
        for model in get_models(app):
            if model.__name__ == model_name:
                form = modelform_factory(model)
                return form

    raise Exception('Did not find the model %s' % (model_name))
Beispiel #44
0
def run():
    for app_mod in get_apps():
        app_models = get_models(app_mod)
        for model in app_models:
            try:
                print model.__module__, model.__name__, model.objects.all(
                ).count()
            except Exception, e:
                print e
    def handle(self, *args, **options):
        all_indexes = []
        proposed_indexes = {}
        index_sql = {}
        for app in get_apps():
            all_indexes.append(u'\n'.join(sql_indexes(app,
                                                      no_style(),
                                                      connection)).encode('utf-8'))
        #Sort out all the proposed indexes by table.
        for index in all_indexes:
            indice = index.split('\n')
            for ind in indice:
                try:
                    match = index_re.search(ind)
                    name, table, field = match.groups()
                    if table in proposed_indexes:
                        proposed_indexes[table].append(name)
                    else:
                        proposed_indexes[table] = [name]
                    if name in index_sql:
                        index_sql[name].append(ind)
                    else:
                        index_sql[name] = [ind]
                except:
                    pass

        #Now get all the real indexes.
        indexes = {}
        cursor = connection.cursor()
        vals = cursor.execute(CURRENT_INDEX_SQL)
        sql_back = cursor.fetchall()
        for row in sql_back:
            name, table = row
            if table in indexes:
                indexes[table].append(name)
            else:
                indexes[table] = [name]

        #For all the proposed indexes, see if they exist
        #If not, tell us!
        for prop_name, prop_tables in proposed_indexes.items():
            for table in prop_tables:
                try:
                    if not table in indexes[prop_name]:
                        if not options['show']:
                            logger.info("(%s, %s) is missing", prop_name, table)
                        else:
                            for index in index_sql[table]:
                                if prop_name in index:
                                    logger.info(index)
                except KeyError:
                    if not options['show']:
                        logger.info("No Indexes for %s in original db", prop_name)
                    else:
                        for index in index_sql[table]:
                            if table in index:
                                logger.info(index)
Beispiel #46
0
def get_all_jobs():
    jobs = []

    for app in get_apps():
        try:
            module = importlib.import_module(app.__name__[:-6] + 'jobs')
            jobs.extend(get_jobs_from_module(module))
        except ImportError:
            pass

    return jobs
Beispiel #47
0
 def handle(self, *args, **options):
     if len(args) < 1:
         if options['all_applications']:
             applications = get_apps()
         else:
             raise CommandError("need one or more arguments for appname")
     else:
         try:
             applications = [get_app(label) for label in args]
         except ImproperlyConfigured, e:
             raise CommandError("Specified application not found: %s" % e)
Beispiel #48
0
 def handle_noargs(self, **options):
     for app in get_apps():
         for model in get_models(app):
             if issubclass(model, SlugifiedModel):
                 print 'Slugifying %s' % model._meta.verbose_name_plural
                 i = 0
                 for obj in model._default_manager.all().iterator():
                     obj.save()
                     i += 1
                     if not i % 100:
                         print '%d %s slugified' % (
                             i, model._meta.verbose_name_plural)
Beispiel #49
0
    def _get_containing_app(object_name):
        candidates = []
        for app_config in loading.get_apps():
            if app_config.__package__ is None:
                app_config.__package__ = app_config.__name__.rpartition('.')[0]

            if object_name.startswith(app_config.__package__):
                subpath = object_name[len(app_config.__package__):]
                if subpath == '' or subpath[0] == '.':
                    candidates.append(app_config)
        if candidates:
            return sorted(candidates, key=lambda ac: -len(ac.__package__))[0]
Beispiel #50
0
def _cache():
    if _APP_NAMES_CACHE:
        return
    for app in get_apps():
        for model in get_models(app, include_auto_created=True):
            model_name = model._meta.object_name.lower()
            app_name = model._meta.app_label.lower()
            _APP_NAMES_CACHE[model_name].add(app_name)
            _MODEL_CACHE[model_label(model)] = model
    for model_name, app_labels in _APP_NAMES_CACHE.items():
        if len(app_labels) == 1:
            model = _MODEL_CACHE[model_label(list(app_labels)[0], model_name)]
            _MODEL_CACHE[model_name] = model
Beispiel #51
0
    def get_app_paths():
        """
        Returns a list of paths to all installed apps.

        Useful for discovering files at conventional locations inside apps
        (static files, templates, etc.)
        """
        app_paths = []
        for app in get_apps():
            if hasattr(app, '__path__'):        # models/__init__.py package
                app_paths.extend([upath(path) for path in app.__path__])
            else:                               # models.py module
                app_paths.append(upath(app.__file__))
        return app_paths
Beispiel #52
0
def django_tests(verbosity, interactive, failfast, test_labels):
    from django.conf import settings

    old_installed_apps = settings.INSTALLED_APPS
    old_root_urlconf = getattr(settings, "ROOT_URLCONF", "")
    old_template_dirs = settings.TEMPLATE_DIRS
    old_use_i18n = settings.USE_I18N
    old_login_url = settings.LOGIN_URL
    old_language_code = settings.LANGUAGE_CODE
    old_middleware_classes = settings.MIDDLEWARE_CLASSES

    # Load all the ALWAYS_INSTALLED_APPS.
    # (This import statement is intentionally delayed until after we
    # access settings because of the USE_I18N dependency.)
    from django.db.models.loading import get_apps, load_app
    get_apps()

    # Load all the test model apps.
    for model_dir, model_name in get_test_models():
        model_label = '.'.join([model_dir, model_name])
        try:
            # if the model was named on the command line, or
            # no models were named (i.e., run all), import
            # this model and add it to the list to test.
            if not test_labels or model_name in set(
                [label.split('.')[0] for label in test_labels]):
                if verbosity >= 1:
                    print "Importing model %s" % model_name
                mod = load_app(model_label)
                if mod:
                    if model_label not in settings.INSTALLED_APPS:
                        settings.INSTALLED_APPS.append(model_label)
        except Exception, e:
            sys.stderr.write(
                "Error while importing %s:" % model_name +
                ''.join(traceback.format_exception(*sys.exc_info())[1:]))
            continue
Beispiel #53
0
def _get_all_models(filter_app_name=None):
    all_models = []
    if filter_app_name:
        apps = [get_app(filter_app_name)]
    else:
        apps = get_apps()
    from django.contrib.admin import site

    for app in apps:
        for mod in get_models(app):
            if mod in site._registry:
                all_models.append("%s:%s" %
                                  (mod._meta.app_label,
                                   force_unicode(mod._meta.verbose_name)))
    return zip(all_models, all_models)
Beispiel #54
0
def get_model_form(model_name):
    app_list = get_apps()
    for app in app_list:
        for model in get_models(app):
            if model.__name__ == model_name:
                try:
                    # add_new_form is a class method
                    # that can be used to specialize the form
                    form = model.add_new_form()
                except AttributeError:
                    form = None
                if not form:
                    form = modelform_factory(model)
                return form

    raise Exception('Did not find the model %s' % (model_name))
Beispiel #55
0
    def __init__(self, *app_names):
        """
        app_names: One or more fully qualified django app names

        ie: api = AutoAPI('django.contrib.auth', 'example')
        """
        self.api = Api()
        apps = []
        if app_names:
            for app in app_names:
                app = load_app(app)
                apps.append(app)
        else:
            # Add all the apps if none are specified
            apps = get_apps()
        for app in apps:
            self.register_app(app)
Beispiel #56
0
def add_new_model(request, model_name):
    if (model_name.lower() == model_name):
        normal_model_name = model_name.capitalize()
    else:
        normal_model_name = model_name

    current_user = request.user
    current_profile = current_user.profile
    current_organization = current_profile and current_profile.organization

    auto_fields = {
        'organization': current_organization,
    }

    app_list = get_apps()
    for app in app_list:
        for model in get_models(app):
            if model.__name__ == normal_model_name:
                # Try to get a form based on model, if you can.
                form = getattr(sfpirg_forms, '%sForm' % normal_model_name,
                               None) or modelform_factory(model)

                if request.method == 'POST':
                    form = form(request.POST)
                    if form.is_valid():
                        try:
                            new_obj = form.save()
                        except forms.ValidationError, error:
                            new_obj = None

                        if new_obj:
                            return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % \
                                (escape(new_obj._get_pk_val()), escape(new_obj)))

                else:
                    form = form()
                for fieldname, field in form.fields.items():
                    if fieldname in auto_fields:
                        field.initial = auto_fields[fieldname]
                        field.widget = forms.HiddenInput()

                page_context = {'form': form, 'field': normal_model_name}
                return render_to_response(
                    'popup.html',
                    page_context,
                    context_instance=RequestContext(request))