Beispiel #1
0
    def handle_noargs(self, **options):
        verbosity = int(options['verbosity'])
        if verbosity > 0:
            self.stdout.write("Using default language: %s\n" %
                              DEFAULT_LANGUAGE)
        models = translator.get_registered_models(abstract=False)
        for model in models:
            if verbosity > 0:
                self.stdout.write("Updating data of model '%s'\n" % model)
            opts = translator.get_options_for_model(model)
            for field_name in opts.fields.keys():
                def_lang_fieldname = build_localized_fieldname(
                    field_name, DEFAULT_LANGUAGE)

                # We'll only update fields which do not have an existing value
                q = Q(**{def_lang_fieldname: None})
                field = model._meta.get_field(field_name)
                if field.empty_strings_allowed:
                    q |= Q(**{def_lang_fieldname: ''})

                if issubclass(model, Page):
                    for obj in model._default_manager.filter(q):
                        # Get table description in order to know if field is
                        # in child or parent table
                        # TODO: Tested only on PostgreSQL engine
                        db_table = model._meta.db_table
                        db_table_desc = connection.introspection.\
                            get_table_description(
                                connection.cursor(), db_table)
                        # original field in child class
                        if field_name in [x.name for x in db_table_desc]:
                            raw = model._default_manager.raw(
                                'SELECT *, %s AS original_field FROM %s \
                                 WHERE page_ptr_id=%d LIMIT 1' %
                                (field_name, db_table, obj.page_ptr_id))[0]
                            setattr(obj, def_lang_fieldname,
                                    raw.original_field)
                        # field is a foreign key
                        elif (field_name + '_id') in\
                                [x.name for x in db_table_desc]:
                            raw = model._default_manager.raw(
                                'SELECT *, %s AS original_field FROM %s \
                                 WHERE page_ptr_id=%d LIMIT 1' %
                                (field_name + '_id', db_table,
                                 obj.page_ptr_id))[0]
                            setattr(obj, def_lang_fieldname + '_id',
                                    raw.original_field)
                        # original field parent class
                        else:
                            raw = Page._default_manager.raw(
                                'SELECT *, %s AS original_field FROM \
                                 wagtailcore_page WHERE id=%d LIMIT 1' %
                                (field_name, obj.page_ptr_id))[0]
                            setattr(obj, def_lang_fieldname,
                                    raw.original_field)
                        obj.save(update_fields=[def_lang_fieldname])
                else:
                    model._default_manager.filter(q).rewrite(False).update(
                        **{def_lang_fieldname: F(field_name)})
def autodiscover():
    """
    Auto-discover INSTALLED_APPS translation.py modules and fail silently when
    not present. This forces an import on them to register.
    Also import explicit modules.
    """
    import os
    import sys
    import copy
    from django.conf import settings
    from django.utils.module_loading import module_has_submodule
    from wagtail_modeltranslation.translator import translator
    from wagtail_modeltranslation.settings import TRANSLATION_FILES, DEBUG

    if django.VERSION < (1, 7):
        from django.utils.importlib import import_module
        mods = [(app, import_module(app)) for app in settings.INSTALLED_APPS]
    else:
        from importlib import import_module
        from django.apps import apps
        mods = [(app_config.name, app_config.module)
                for app_config in apps.get_app_configs()]

    for (app, mod) in mods:
        # Attempt to import the app's translation module.
        module = '%s.translation' % app
        before_import_registry = copy.copy(translator._registry)
        try:
            import_module(module)
        except:
            # Reset the model registry to the state before the last import as
            # this import will have to reoccur on the next request and this
            # could raise NotRegistered and AlreadyRegistered exceptions
            translator._registry = before_import_registry

            # Decide whether to bubble up this error. If the app just
            # doesn't have an translation module, we can ignore the error
            # attempting to import it, otherwise we want it to bubble up.
            if module_has_submodule(mod, 'translation'):
                raise

    for module in TRANSLATION_FILES:
        import_module(module)

    # In debug mode, print a list of registered models and pid to stdout.
    # Note: Differing model order is fine, we don't rely on a particular
    # order, as far as base classes are registered before subclasses.
    if DEBUG:
        try:
            if sys.argv[1] in ('runserver', 'runserver_plus'):
                models = translator.get_registered_models()
                names = ', '.join(m.__name__ for m in models)
                print('wagtail_modeltranslation: Registered %d models for '
                      'translation (%s) [pid: %d].' %
                      (len(models), names, os.getpid()))
        except IndexError:
            pass
def autodiscover():
    """
    Auto-discover INSTALLED_APPS translation.py modules and fail silently when
    not present. This forces an import on them to register.
    Also import explicit modules.
    """
    import os
    import sys
    import copy
    from django.conf import settings
    from django.utils.module_loading import module_has_submodule
    from wagtail_modeltranslation.translator import translator
    from wagtail_modeltranslation.settings import TRANSLATION_FILES, DEBUG

    if django.VERSION < (1, 7):
        from django.utils.importlib import import_module
        mods = [(app, import_module(app)) for app in settings.INSTALLED_APPS]
    else:
        from importlib import import_module
        from django.apps import apps
        mods = [(app_config.name, app_config.module) for app_config in apps.get_app_configs()]

    for (app, mod) in mods:
        # Attempt to import the app's translation module.
        module = '%s.translation' % app
        before_import_registry = copy.copy(translator._registry)
        try:
            import_module(module)
        except:
            # Reset the model registry to the state before the last import as
            # this import will have to reoccur on the next request and this
            # could raise NotRegistered and AlreadyRegistered exceptions
            translator._registry = before_import_registry

            # Decide whether to bubble up this error. If the app just
            # doesn't have an translation module, we can ignore the error
            # attempting to import it, otherwise we want it to bubble up.
            if module_has_submodule(mod, 'translation'):
                raise

    for module in TRANSLATION_FILES:
        import_module(module)

    # In debug mode, print a list of registered models and pid to stdout.
    # Note: Differing model order is fine, we don't rely on a particular
    # order, as far as base classes are registered before subclasses.
    if DEBUG:
        try:
            if sys.argv[1] in ('runserver', 'runserver_plus'):
                models = translator.get_registered_models()
                names = ', '.join(m.__name__ for m in models)
                print('wagtail_modeltranslation: Registered %d models for translation'
                      ' (%s) [pid: %d].' % (len(models), names, os.getpid()))
        except IndexError:
            pass
    def handle_noargs(self, **options):
        verbosity = int(options['verbosity'])
        if verbosity > 0:
            self.stdout.write(
                "Using default language: %s\n" % DEFAULT_LANGUAGE)
        models = translator.get_registered_models(abstract=False)
        for model in models:
            if verbosity > 0:
                self.stdout.write("Updating data of model '%s'\n" % model)
            opts = translator.get_options_for_model(model)
            for field_name in opts.fields.keys():
                def_lang_fieldname = build_localized_fieldname(
                    field_name, DEFAULT_LANGUAGE)

                # We'll only update fields which do not have an existing value
                q = Q(**{def_lang_fieldname: None})
                field = model._meta.get_field(field_name)
                if field.empty_strings_allowed:
                    q |= Q(**{def_lang_fieldname: ''})

                if issubclass(model, Page):
                    for obj in model._default_manager.filter(q):
                        # Get table description in order to know if field is
                        # in child or parent table
                        # TODO: Tested only on PostgreSQL engine
                        db_table = model._meta.db_table
                        db_table_desc = connection.introspection.\
                            get_table_description(
                                connection.cursor(), db_table)
                        # original field in child class
                        if field_name in [x.name for x in db_table_desc]:
                            raw = model._default_manager.raw(
                                'SELECT *, %s AS original_field FROM %s \
                                 WHERE page_ptr_id=%d LIMIT 1' % (
                                    field_name, db_table, obj.page_ptr_id))[0]
                            setattr(
                                obj, def_lang_fieldname, raw.original_field)
                        # original field parent class
                        else:
                            raw = Page._default_manager.raw(
                                'SELECT *, %s AS original_field FROM \
                                 wagtailcore_page WHERE id=%d LIMIT 1' % (
                                    field_name, obj.page_ptr_id))[0]
                            setattr(
                                obj, def_lang_fieldname, raw.original_field)
                        obj.save(update_fields=[def_lang_fieldname])
                else:
                    model._default_manager.filter(q).rewrite(False).update(
                        **{def_lang_fieldname: F(field_name)})
Beispiel #5
0
    def handle_noargs(self, **options):
        """
        Command execution.
        """
        self.cursor = connection.cursor()
        self.introspection = connection.introspection
        self.interactive = options['interactive']

        found_missing_fields = False
        models = translator.get_registered_models(abstract=False)
        for model in models:
            db_table = model._meta.db_table
            if django.VERSION < (1, 8):
                model_name = model._meta.module_name
            else:
                model_name = model._meta.model_name
            model_full_name = '%s.%s' % (model._meta.app_label, model_name)
            opts = translator.get_options_for_model(model)
            for field_name, fields in opts.local_fields.items():
                # Take `db_column` attribute into account
                field = list(fields)[0]
                column_name = field.db_column if field.db_column else field_name
                missing_langs = list(
                    self.get_missing_languages(column_name, db_table))
                if missing_langs:
                    found_missing_fields = True
                    print_missing_langs(missing_langs, field_name,
                                        model_full_name)
                    sql_sentences = self.get_sync_sql(field_name,
                                                      missing_langs, model)
                    execute_sql = ask_for_confirmation(sql_sentences,
                                                       model_full_name,
                                                       self.interactive)
                    if execute_sql:
                        print('Executing SQL...')
                        for sentence in sql_sentences:
                            self.cursor.execute(sentence)
                        print('Done')
                    else:
                        print('SQL not executed')

        if django.VERSION < (1, 6):
            transaction.commit_unless_managed()

        if not found_missing_fields:
            print('No new translatable fields detected')
    def handle_noargs(self, **options):
        """
        Command execution.
        """
        self.cursor = connection.cursor()
        self.introspection = connection.introspection
        self.interactive = options['interactive']

        found_missing_fields = False
        models = translator.get_registered_models(abstract=False)
        for model in models:
            db_table = model._meta.db_table
            if django.VERSION < (1, 8):
                model_name = model._meta.module_name
            else:
                model_name = model._meta.model_name
            model_full_name = '%s.%s' % (model._meta.app_label, model_name)
            opts = translator.get_options_for_model(model)
            for field_name, fields in opts.local_fields.items():
                # Take `db_column` attribute into account
                field = list(fields)[0]
                column_name = field.db_column if field.db_column else field_name
                missing_langs = list(self.get_missing_languages(column_name, db_table))
                if missing_langs:
                    found_missing_fields = True
                    print_missing_langs(missing_langs, field_name, model_full_name)
                    sql_sentences = self.get_sync_sql(field_name, missing_langs, model)
                    execute_sql = ask_for_confirmation(
                        sql_sentences, model_full_name, self.interactive)
                    if execute_sql:
                        print('Executing SQL...')
                        for sentence in sql_sentences:
                            self.cursor.execute(sentence)
                        print('Done')
                    else:
                        print('SQL not executed')

        if django.VERSION < (1, 6):
            transaction.commit_unless_managed()

        if not found_missing_fields:
            print('No new translatable fields detected')
    def handle_noargs(self, **options):
        verbosity = int(options['verbosity'])
        if verbosity > 0:
            self.stdout.write("Using default language: %s\n" % DEFAULT_LANGUAGE)
        models = translator.get_registered_models(abstract=False)
        for model in models:
            if verbosity > 0:
                self.stdout.write("Updating data of model '%s'\n" % model)
            opts = translator.get_options_for_model(model)
            for field_name in opts.fields.keys():
                def_lang_fieldname = build_localized_fieldname(field_name, DEFAULT_LANGUAGE)

                # We'll only update fields which do not have an existing value
                q = Q(**{def_lang_fieldname: None})
                field = model._meta.get_field(field_name)
                if field.empty_strings_allowed:
                    q |= Q(**{def_lang_fieldname: ""})

                model._default_manager.filter(q).rewrite(False).update(
                    **{def_lang_fieldname: F(field_name)})
    def handle_noargs(self, **options):
        verbosity = int(options['verbosity'])
        if verbosity > 0:
            self.stdout.write("Using default language: %s\n" %
                              DEFAULT_LANGUAGE)
        models = translator.get_registered_models(abstract=False)
        for model in models:
            if verbosity > 0:
                self.stdout.write("Updating data of model '%s'\n" % model)
            opts = translator.get_options_for_model(model)
            for field_name in opts.fields.keys():
                def_lang_fieldname = build_localized_fieldname(
                    field_name, DEFAULT_LANGUAGE)

                # We'll only update fields which do not have an existing value
                q = Q(**{def_lang_fieldname: None})
                field = model._meta.get_field(field_name)
                if field.empty_strings_allowed:
                    q |= Q(**{def_lang_fieldname: ""})

                model._default_manager.filter(q).rewrite(False).update(
                    **{def_lang_fieldname: F(field_name)})