django.apps.apps.get_app_configs

Here are the examples of the python api django.apps.apps.get_app_configs taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

138 Examples 7

Example 1

Project: dre Source File: __init__.py
def load_indexes():
    from djapian.utils import loading
    for app_config in apps.get_app_configs():
        try:
            module = app_config.module.__name__
            loading.get_module(module, "index")
        except loading.NoModuleError:
            pass

Example 2

Project: django-pgviews Source File: apps.py
    def sync_pgviews(self, sender, app_config, **kwargs):
        """Forcibly sync the views.
        """
        self.counter = self.counter + 1
        total = len([a for a in apps.apps.get_app_configs() if a.models_module is not None])
        
        if self.counter == total:
            log.info('All applications have migrated, time to sync')
            # Import here otherwise Django doesn't start properly
            # (models in app init are not allowed)
            from .models import ViewSyncer
            vs = ViewSyncer()
            vs.run(force=True, update=True) 

Example 3

Project: SHARE Source File: runbot.py
    def handle(self, *args, **options):
        user = ShareUser.objects.get(username=settings.APPLICATION_USERNAME)

        if not options['bot'] and options['all']:
            options['bot'] = [x.label for x in apps.get_app_configs() if isinstance(x, BotAppConfig)]

        for bot in options['bot']:
            apps.get_app_config(bot)  # Die if the AppConfig can not be loaded

            task_args = (bot, user.id,)
            task_kwargs = {'last_run': options['last_run']}

            if options['async']:
                BotTask().apply_async(task_args, task_kwargs)
                self.stdout.write('Started job for bot {}'.format(bot))
            else:
                self.stdout.write('Running bot for {}'.format(bot))
                BotTask().apply(task_args, task_kwargs, throw=True)

Example 4

Project: django-bmf Source File: testcases.py
Function: set_up
    def setUp(self):  # noqa
        super(BaseTestCase, self).setUp()
        self.user = self.create_user("superuser", is_superuser=True)
        self.client_login("superuser")
        self.appconf = [app for app in apps.get_app_configs() if isinstance(app, self.app)][0]
        self.models = [m for m in self.appconf.get_models() if config.has_module(m)]

Example 5

Project: django-sellmo Source File: base.py
def should_fix_type(typ):
    global allowed
    if allowed is None:
        allowed = ['sellmo']
        for app in apps.get_app_configs():
            allowed.append(app.name)
    return any(typ.__module__.startswith(name) for name in allowed)

Example 6

Project: wagtail Source File: apps.py
Function: get_app_modules
def get_app_modules():
    """
    Generator function that yields a module object for each installed app
    yields tuples of (app_name, module)
    """
    for app in apps.get_app_configs():
        yield app.name, app.module

Example 7

Project: django-sass-processor Source File: apps.py
Function: ready
    def ready(self):
        if self._auto_include:
            app_configs = apps.get_app_configs()
            for app_config in app_configs:
                static_dir = os.path.join(app_config.path, self._storage.base_url.strip(os.path.sep))
                if os.path.isdir(static_dir):
                    self.traverse_tree(static_dir)

Example 8

Project: django-cassandra-engine Source File: utils.py
def get_installed_apps():
    """
    Return list of all installed apps
    """
    if django.VERSION >= (1, 7):
        from django.apps import apps
        return [a.models_module for a in apps.get_app_configs()
                if a.models_module is not None]
    else:
        from django.db import models
        return models.get_apps()

Example 9

Project: horizon Source File: finders.py
Function: init
    def __init__(self, app_names=None, *args, **kwargs):
        super(HorizonStaticFinder, self).__init__(*args, **kwargs)
        app_configs = apps.get_app_configs()
        for app_config in app_configs:
            if 'openstack_dashboard' in app_config.path:
                for panel in os.listdir(app_config.path):
                    panel_path = os.path.join(app_config.path, panel)
                    if os.path.isdir(panel_path) and panel != self.source_dir:

                        # Look for the static folder
                        static_path = os.path.join(panel_path, self.source_dir)
                        if os.path.isdir(static_path):
                            panel_name = app_config.name + panel
                            app_storage = self.storage_class(static_path)
                            self.storages[panel_name] = app_storage

Example 10

Project: Django--an-app-at-a-time Source File: introspection.py
    def installed_models(self, tables):
        "Returns a set of all models represented by the provided list of table names."
        from django.apps import apps
        from django.db import router
        all_models = []
        for app_config in apps.get_app_configs():
            all_models.extend(router.get_migratable_models(app_config, self.connection.alias))
        tables = list(map(self.table_name_converter, tables))
        return {
            m for m in all_models
            if self.table_name_converter(m._meta.db_table) in tables
        }

Example 11

Project: django-admin-tools Source File: template_loaders.py
Function: get_app_template_dir
def get_app_template_dir(app_name):
    """Get the template directory for an application

    Uses apps interface available in django 1.7+

    Returns a full path, or None if the app was not found.
    """
    if app_name in _cache:
        return _cache[app_name]
    template_dir = None
    for app in apps.get_app_configs():
        if app.label == app_name:
            template_dir = join(app.path, 'templates')
            break
    _cache[app_name] = template_dir
    return template_dir

Example 12

Project: django Source File: sql.py
Function: emit_post_migrate_signal
def emit_post_migrate_signal(verbosity, interactive, db, **kwargs):
    # Emit the post_migrate signal for every application.
    for app_config in apps.get_app_configs():
        if app_config.models_module is None:
            continue
        if verbosity >= 2:
            print("Running post-migrate handlers for application %s" % app_config.label)
        models.signals.post_migrate.send(
            sender=app_config,
            app_config=app_config,
            verbosity=verbosity,
            interactive=interactive,
            using=db,
            **kwargs
        )

Example 13

Project: shuup Source File: i18n.py
@cache_page(3600, key_prefix="js18n-%s" % get_language())
def javascript_catalog_all(request, domain='djangojs'):
    """
    Get JavaScript message catalog for all apps in INSTALLED_APPS.
    """
    all_apps = [x.name for x in apps.get_app_configs()]
    return javascript_catalog(request, domain, all_apps)

Example 14

Project: django-app-namespace-template-loader Source File: loader.py
    @cached_property
    def app_templates_dirs(self):
        """
        Build a cached dict with settings.INSTALLED_APPS as keys
        and the 'templates' directory of each application as values.
        """
        app_templates_dirs = OrderedDict()
        for app_config in apps.get_app_configs():
            templates_dir = os.path.join(
                getattr(app_config, 'path', '/'), 'templates')
            if os.path.isdir(templates_dir):
                templates_dir = upath(templates_dir)
                app_templates_dirs[app_config.name] = templates_dir
                app_templates_dirs[app_config.label] = templates_dir
        return app_templates_dirs

Example 15

Project: PyClassLessons Source File: app_directories.py
def calculate_app_template_dirs():
    if six.PY2:
        fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
    app_template_dirs = []
    for app_config in apps.get_app_configs():
        if not app_config.path:
            continue
        template_dir = os.path.join(app_config.path, 'templates')
        if os.path.isdir(template_dir):
            if six.PY2:
                template_dir = template_dir.decode(fs_encoding)
            app_template_dirs.append(template_dir)
    return tuple(app_template_dirs)

Example 16

Project: django-debug-toolbar Source File: versions.py
    def gen_app_versions(self):
        for app_config in apps.get_app_configs():
            name = app_config.verbose_name
            app = app_config.module
            version = self.get_app_version(app)
            if version:
                yield app.__name__, name, version

Example 17

Project: django-mysql Source File: fix_datetime_columns.py
    def all_table_names(self):
        table_names = set()
        for app_config in apps.get_app_configs():
            for model in app_config.get_models():
                table_names.add(model._meta.db_table)
        return list(sorted(table_names))

Example 18

Project: karaage Source File: __init__.py
def get_app_modules(name):
    if django.VERSION < (1, 7):
        for app in settings.INSTALLED_APPS:
            try:
                module_name = app + "." + name
                module = importlib.import_module(module_name)
                yield module
            except ImportError:
                pass
    else:
        from django.apps import apps
        for config in apps.get_app_configs():
            if isinstance(config, BasePlugin):
                module_name = config.name + "." + name
                module = importlib.import_module(module_name)
                yield module

Example 19

Project: PyClassLessons Source File: finders.py
Function: init
    def __init__(self, app_names=None, *args, **kwargs):
        # The list of apps that are handled
        self.apps = []
        # Mapping of app names to storage instances
        self.storages = OrderedDict()
        app_configs = apps.get_app_configs()
        if app_names:
            app_names = set(app_names)
            app_configs = [ac for ac in app_configs if ac.name in app_names]
        for app_config in app_configs:
            app_storage = self.storage_class(
                os.path.join(app_config.path, self.source_dir))
            if os.path.isdir(app_storage.location):
                self.storages[app_config.name] = app_storage
                if app_config.name not in self.apps:
                    self.apps.append(app_config.name)
        super(AppDirectoriesFinder, self).__init__(*args, **kwargs)

Example 20

Project: smartmin Source File: __init__.py
def get_permissions_app_name():
    """
    Gets the app after which smartmin permissions should be installed. This can be specified by PERMISSIONS_APP in the
    Django settings or defaults to the last app with models
    """
    global permissions_app_name

    if not permissions_app_name:
        permissions_app_name = getattr(settings, 'PERMISSIONS_APP', None)

        if not permissions_app_name:
            app_names_with_models = [a.name for a in apps.get_app_configs() if a.models_module is not None]
            if app_names_with_models:
                permissions_app_name = app_names_with_models[-1]

    return permissions_app_name

Example 21

Project: cgstudiomap Source File: sql.py
Function: emit_post_migrate_signal
def emit_post_migrate_signal(verbosity, interactive, db):
    # Emit the post_migrate signal for every application.
    for app_config in apps.get_app_configs():
        if app_config.models_module is None:
            continue
        if verbosity >= 2:
            print("Running post-migrate handlers for application %s" % app_config.label)
        models.signals.post_migrate.send(
            sender=app_config,
            app_config=app_config,
            verbosity=verbosity,
            interactive=interactive,
            using=db)

Example 22

Project: cgstudiomap Source File: eggs.py
Function: get_template_sources
    def get_template_sources(self, template_name):
        pkg_name = 'templates/' + template_name
        for app_config in apps.get_app_configs():
            yield EggOrigin(
                app_name=app_config.name,
                pkg_name=pkg_name,
                name="egg:%s:%s" % (app_config.name, pkg_name),
                template_name=template_name,
                loader=self,
            )

Example 23

Project: pretix Source File: plugins.py
Function: get_all_plugins
def get_all_plugins() -> List[type]:
    """
    Returns the PretixPluginMeta classes of all plugins found in the installed Django apps.
    """
    plugins = []
    for app in apps.get_app_configs():
        if hasattr(app, 'PretixPluginMeta'):
            meta = app.PretixPluginMeta
            meta.module = app.name
            meta.app = app
            plugins.append(meta)
    return plugins

Example 24

Project: django Source File: sql.py
Function: emit_pre_migrate_signal
def emit_pre_migrate_signal(verbosity, interactive, db, **kwargs):
    # Emit the pre_migrate signal for every application.
    for app_config in apps.get_app_configs():
        if app_config.models_module is None:
            continue
        if verbosity >= 2:
            print("Running pre-migrate handlers for application %s" % app_config.label)
        models.signals.pre_migrate.send(
            sender=app_config,
            app_config=app_config,
            verbosity=verbosity,
            interactive=interactive,
            using=db,
            **kwargs
        )

Example 25

Project: Django--an-app-at-a-time Source File: eggs.py
    def load_template_source(self, template_name, template_dirs=None):
        """
        Loads templates from Python eggs via pkg_resource.resource_string.

        For every installed app, it tries to get the resource (app, template_name).
        """
        if resource_string is not None:
            pkg_name = 'templates/' + template_name
            for app_config in apps.get_app_configs():
                try:
                    resource = resource_string(app_config.name, pkg_name)
                except Exception:
                    continue
                if six.PY2:
                    resource = resource.decode(self.engine.file_charset)
                return (resource, 'egg:%s:%s' % (app_config.name, pkg_name))
        raise TemplateDoesNotExist(template_name)

Example 26

Project: django Source File: tests.py
    def test_app_completion(self):
        "Application names will be autocompleted for an AppCommand"
        self._user_input('django-admin sqlmigrate a')
        output = self._run_autocomplete()
        a_labels = sorted(
            app_config.label for app_config in apps.get_app_configs()
            if app_config.label.startswith('a')
        )
        self.assertEqual(output, a_labels)

Example 27

Project: django Source File: trans_real.py
    def _add_installed_apps_translations(self):
        """Merges translations from each installed app."""
        try:
            app_configs = reversed(list(apps.get_app_configs()))
        except AppRegistryNotReady:
            raise AppRegistryNotReady(
                "The translation infrastructure cannot be initialized before the "
                "apps registry is ready. Check that you don't make non-lazy "
                "gettext calls at import time.")
        for app_config in app_configs:
            localedir = os.path.join(app_config.path, 'locale')
            if os.path.exists(localedir):
                translation = self._new_gnu_trans(localedir)
                self.merge(translation)

Example 28

Project: Django--an-app-at-a-time Source File: trans_real.py
Function: add_installed_apps_translations
    def _add_installed_apps_translations(self):
        """Merges translations from each installed app."""
        try:
            app_configs = reversed(list(apps.get_app_configs()))
        except AppRegistryNotReady:
            raise AppRegistryNotReady(
                "The translation infrastructure cannot be initialized before the "
                "apps registry is ready. Check that you don't make non-lazy "
                "gettext calls at import time.")
        for app_config in app_configs:
            localedir = os.path.join(app_config.path, 'locale')
            translation = self._new_gnu_trans(localedir)
            self.merge(translation)

Example 29

Project: django-bmf Source File: apps.py
Function: ready
    def ready(self):
        # Autoloader
        for module in ['bmf_module', 'bmf_relation']:
            for app_config in apps.get_app_configs():
                # app_config.bmfconfig = self
                try:
                    import_module('%s.%s' % (app_config.name, module))
                except:
                    if module_has_submodule(app_config.module, module):
                        raise

Example 30

Project: djangae Source File: indexing.py
def _get_app_index_files():
    index_files = []

    for app_config in apps.get_app_configs():
        app_path = app_config.path
        project_index_file = os.path.join(app_path, "djangaeidx.yaml")
        index_files.append(project_index_file)
    return index_files

Example 31

Project: django-mako-plus Source File: util.py
def get_dmp_app_configs():
    '''
    Gets the DMP-enabled app configs, which will be a subset of all installed apps.  This is a generator function.
    '''
    for config in apps.get_app_configs():
        # check for the DJANGO_MAKO_PLUS = True in the app (should be in app/__init__.py)
        if getattr(config.module, 'DJANGO_MAKO_PLUS', False):
            yield config

Example 32

Project: django-natural-query Source File: apps.py
Function: ready
    def ready(self):
        """
        Temporary code that monkeypatches the model classes.
        """
        app_configs = apps.get_app_configs()
        models = tuple(itertools.chain.from_iterable(app_config.get_models() for app_config in app_configs))

        for model in models:
            self.naturalize_model(model)

        for model in models:
            self.naturalize_model_relationships(model)

Example 33

Project: django-recommends Source File: apps.py
Function: ready
    def ready(self):
        if not RECOMMENDS_AUTODISCOVER_MODULE:
            return

        for appconfig in apps.get_app_configs():
            try:
                importlib.import_module('.' + RECOMMENDS_AUTODISCOVER_MODULE, appconfig.name)
            except ImportError:
                pass

Example 34

Project: cgstudiomap Source File: sql.py
Function: emit_pre_migrate_signal
def emit_pre_migrate_signal(verbosity, interactive, db):
    # Emit the pre_migrate signal for every application.
    for app_config in apps.get_app_configs():
        if app_config.models_module is None:
            continue
        if verbosity >= 2:
            print("Running pre-migrate handlers for application %s" % app_config.label)
        models.signals.pre_migrate.send(
            sender=app_config,
            app_config=app_config,
            verbosity=verbosity,
            interactive=interactive,
            using=db)

Example 35

Project: sqjobs Source File: finders.py
def get_apps_names():
    """
    copied from django-extensions compatibility sheam
    """
    try:
        # django >= 1.7, to support AppConfig
        from django.apps import apps
        return [app.name for app in apps.get_app_configs()]
    except ImportError:
        from django.db import models
        return [app.__name__[:-7] for app in models.get_apps()]

Example 36

Project: nodewatcher Source File: loader.py
def load_modules(*types):
    """
    Loads the per-application specific modules that must always be loaded
    before registry operations can function normally.

    :param types: Types of modules that should be loaded (type name
      determines the filename that is loaded)
    """

    # Note that we can't simply use module_loading.autodiscover_modules as it
    # doesn't work correctly when multiple module types are specified (it exits
    # on the first import failure). See: https://code.djangoproject.com/ticket/23670
    for app in apps.get_app_configs():
        for type in types:
            # Attempt to import the submodule if it exists
            if module_loading.module_has_submodule(app.module, type):
                importlib.import_module(".%s" % type, app.name)

Example 37

Project: jingo Source File: __init__.py
Function: load_helpers
def load_helpers():
    """Try to import ``helpers.py`` from each app in INSTALLED_APPS."""
    # We want to wait as long as possible to load helpers so there aren't any
    # weird circular imports with jingo.
    global _helpers_loaded
    if _helpers_loaded:
        return
    _helpers_loaded = True

    for config in apps.get_app_configs():
        if not has_helpers(config):
            continue

        import_module('%s.helpers' % config.name)

Example 38

Project: PyClassLessons Source File: eggs.py
    def load_template_source(self, template_name, template_dirs=None):
        """
        Loads templates from Python eggs via pkg_resource.resource_string.

        For every installed app, it tries to get the resource (app, template_name).
        """
        if resource_string is not None:
            pkg_name = 'templates/' + template_name
            for app_config in apps.get_app_configs():
                try:
                    resource = resource_string(app_config.name, pkg_name)
                except Exception:
                    continue
                if six.PY2:
                    resource = resource.decode(settings.FILE_CHARSET)
                return (resource, 'egg:%s:%s' % (app_config.name, pkg_name))
        raise TemplateDoesNotExist(template_name)

Example 39

Project: django-sass-processor Source File: compilescss.py
Function: find_sources
    def find_sources(self):
        """
        Look for Python sources available for the current configuration.
        """
        app_configs = apps.get_app_configs()
        for app_config in app_configs:
            ignore_dirs = []
            for root, dirs, files in os.walk(app_config.path):
                if [True for idir in ignore_dirs if root.startswith(idir)]:
                    continue
                if '__init__.py' not in files:
                    ignore_dirs.append(root)
                    continue
                for filename in files:
                    basename, ext = os.path.splitext(filename)
                    if ext != '.py':
                        continue
                    yield os.path.abspath(os.path.join(root, filename))

Example 40

Project: SHARE Source File: admin.py
Function: lookups
    def lookups(self, request, model_admin):
        return sorted([
            (config.label, config.label)
            for config in apps.get_app_configs()
            if isinstance(config, RobotAppConfig)
        ])

Example 41

Project: karaage Source File: karaage_tags.py
def get_app_labels():
    if django.VERSION < (1, 7):
        for app in settings.INSTALLED_APPS:
            _, _, label = app.rpartition(".")
            if label is not None:
                yield label
    else:
        from django.apps import apps
        for config in apps.get_app_configs():
            if isinstance(config, BasePlugin):
                yield config.label

Example 42

Project: django-jinja Source File: base.py
def _iter_templatetags_modules_list():
    """
    Get list of modules that contains templatetags
    submodule.
    """
    from django.apps import apps
    all_modules = [x.name for x in apps.get_app_configs()]

    for app_path in all_modules:
        try:
            mod = import_module(app_path + ".templatetags")
            # Empty folders can lead to unexpected behavior with Python 3.
            # We make sure to have the `__file__` attribute.
            if hasattr(mod, '__file__'):
                yield (app_path, path.dirname(mod.__file__))
        except ImportError:
            pass

Example 43

Project: Misago Source File: discoverer.py
def discover_misago_admin():
    for app in apps.get_app_configs():
        module = import_module(app.name)
        if hasattr(module, 'admin'):
            admin_module = import_module('%s.admin' % app.name)
            if hasattr(admin_module, 'MisagoAdminExtension'):
                extension = getattr(admin_module, 'MisagoAdminExtension')()
                extension.register_navigation_nodes(site)
                extension.register_urlpatterns(urlpatterns)

Example 44

Project: PyClassLessons Source File: flush.py
    @staticmethod
    def emit_post_migrate(verbosity, interactive, database):
        # Emit the post migrate signal. This allows individual applications to
        # respond as if the database had been migrated from scratch.
        all_models = []
        for app_config in apps.get_app_configs():
            all_models.extend(router.get_migratable_models(app_config, database, include_auto_created=True))
        emit_post_migrate_signal(set(all_models), verbosity, interactive, database)

Example 45

Project: Django--an-app-at-a-time Source File: utils.py
@lru_cache.lru_cache()
def get_app_template_dirs(dirname):
    """
    Return an iterable of paths of directories to load app templates from.

    dirname is the name of the subdirectory containing templates inside
    installed applications.
    """
    template_dirs = []
    for app_config in apps.get_app_configs():
        if not app_config.path:
            continue
        template_dir = os.path.join(app_config.path, dirname)
        if os.path.isdir(template_dir):
            template_dirs.append(upath(template_dir))
    # Immutable return value because it will be cached and shared by callers.
    return tuple(template_dirs)

Example 46

Project: django Source File: tests.py
    @override_settings(INSTALLED_APPS=SOME_INSTALLED_APPS)
    def test_get_app_configs(self):
        """
        Tests apps.get_app_configs().
        """
        app_configs = apps.get_app_configs()
        self.assertListEqual(
            [app_config.name for app_config in app_configs],
            SOME_INSTALLED_APPS_NAMES)

Example 47

Project: PyClassLessons Source File: management.py
Function: update_all_contenttypes
def update_all_contenttypes(**kwargs):
    for app_config in apps.get_app_configs():
        update_contenttypes(app_config, **kwargs)

Example 48

Project: PyClassLessons Source File: loaddata.py
Function: fixture_dirs
    @cached_property
    def fixture_dirs(self):
        """
        Return a list of fixture directories.

        The list contains the 'fixtures' subdirectory of each installed
        application, if it exists, the directories in FIXTURE_DIRS, and the
        current directory.
        """
        dirs = []
        for app_config in apps.get_app_configs():
            if self.app_label and app_config.label != self.app_label:
                continue
            app_dir = os.path.join(app_config.path, 'fixtures')
            if os.path.isdir(app_dir):
                dirs.append(app_dir)
        dirs.extend(list(settings.FIXTURE_DIRS))
        dirs.append('')
        dirs = [upath(os.path.abspath(os.path.realpath(d))) for d in dirs]
        return dirs

Example 49

Project: djangae Source File: 0001_patch_contenttypes_migrations.py
def get_installed_app_labels_with_migrations():
    """ Get the app labels, because settings.INSTALLED_APPS doesn't necessarily give us the labels.
        Remove django.contrib.contenttypes because we want it to run before us.
        Return list of tuples like ('admin', '__first__')
    """
    from django.apps import apps
    apps_with_migrations = []
    for app in apps.get_app_configs():
        if app.label == 'contenttypes':
            continue  # Ignore the contenttypes app

        migrations_module = MigrationLoader.migrations_module(app.label)
        try:
            module = import_module(migrations_module)
        except ImportError:
            continue

        if not hasattr(module, "__path__"):
            continue

        # Make sure there are python files in the migration folder (other than the init file)
        has_files = any(
            x for x in os.listdir(module.__path__[0]) if x.endswith(".py") and x != "__init__.py"
        )
        if not has_files:
            continue

        apps_with_migrations.append(app.label)

    return [(x, '__first__') for x in apps_with_migrations]

Example 50

Project: PyClassLessons Source File: flush.py
    def handle_noargs(self, **options):
        database = options.get('database')
        connection = connections[database]
        verbosity = int(options.get('verbosity'))
        interactive = options.get('interactive')
        # The following are stealth options used by Django's internals.
        reset_sequences = options.get('reset_sequences', True)
        allow_cascade = options.get('allow_cascade', False)
        inhibit_post_migrate = options.get('inhibit_post_migrate', False)

        self.style = no_style()

        # Import the 'management' module within each installed app, to register
        # dispatcher events.
        for app_config in apps.get_app_configs():
            try:
                import_module('.management', app_config.name)
            except ImportError:
                pass

        sql_list = sql_flush(self.style, connection, only_django=True,
                             reset_sequences=reset_sequences,
                             allow_cascade=allow_cascade)

        if interactive:
            confirm = input("""You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the %r database,
and return each table to an empty state.
Are you sure you want to do this?

    Type 'yes' to continue, or 'no' to cancel: """ % connection.settings_dict['NAME'])
        else:
            confirm = 'yes'

        if confirm == 'yes':
            try:
                with transaction.atomic(using=database,
                                        savepoint=connection.features.can_rollback_ddl):
                    with connection.cursor() as cursor:
                        for sql in sql_list:
                            cursor.execute(sql)
            except Exception as e:
                new_msg = (
                    "Database %s couldn't be flushed. Possible reasons:\n"
                    "  * The database isn't running or isn't configured correctly.\n"
                    "  * At least one of the expected database tables doesn't exist.\n"
                    "  * The SQL was invalid.\n"
                    "Hint: Look at the output of 'django-admin.py sqlflush'. That's the SQL this command wasn't able to run.\n"
                    "The full error: %s") % (connection.settings_dict['NAME'], e)
                six.reraise(CommandError, CommandError(new_msg), sys.exc_info()[2])

            if not inhibit_post_migrate:
                self.emit_post_migrate(verbosity, interactive, database)

            # Reinstall the initial_data fixture.
            if options.get('load_initial_data'):
                # Reinstall the initial_data fixture for apps without migrations.
                from django.db.migrations.executor import MigrationExecutor
                executor = MigrationExecutor(connection)
                app_options = options.copy()
                for app_label in executor.loader.unmigrated_apps:
                    app_options['app_label'] = app_label
                    call_command('loaddata', 'initial_data', **app_options)
        else:
            self.stdout.write("Flush cancelled.\n")
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3