Python django.utils.translation.deactivate_all() Examples

The following are 7 code examples of django.utils.translation.deactivate_all(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.translation , or try the search function .
Example #1
Source File: test_lookups.py    From django-localized-fields with MIT License 6 votes vote down vote up
def test_localized_lookup(self):
        """Tests whether localized lookup properly works."""

        self.TestModel.objects.create(
            text=LocalizedValue(dict(en="text_en", ro="text_ro", nl="text_nl"))
        )

        # assert that it properly lookups the currently active language
        for lang_code, _ in settings.LANGUAGES:
            translation.activate(lang_code)
            assert self.TestModel.objects.filter(
                text="text_" + lang_code
            ).exists()

        # ensure that the default language is used in case no
        # language is active at all
        translation.deactivate_all()
        assert self.TestModel.objects.filter(text="text_en").exists()

        # ensure that hstore lookups still work
        assert self.TestModel.objects.filter(text__ro="text_ro").exists() 
Example #2
Source File: 0026_remove_specificlocation_color.py    From c3nav with Apache License 2.0 6 votes vote down vote up
def move_all_color_into_groups(apps, schema_editor):
    LocationGroupCategory = apps.get_model('mapdata', 'LocationGroupCategory')
    category = LocationGroupCategory.objects.get(name='groups')

    colors = {}
    for model_name in ('Level', 'Space', 'Area', 'POI'):
        model = apps.get_model('mapdata', model_name)
        for obj in model.objects.filter(color__isnull=False):
            colors.setdefault(obj.color, []).append(obj)

    from c3nav.mapdata.models import Location
    for color, objects in colors.items():
        titles = {lang: [] for lang in set(chain(*(obj.titles.keys() for obj in objects)))}
        for obj in objects:
            for lang in titles.keys():
                translation.activate(lang)
                titles[lang].append(Location(titles=obj.titles).title)
                translation.deactivate_all()
        titles = {lang: ', '.join(values) for lang, values in titles.items()}
        group = category.groups.create(can_search=False, can_describe=False, color=color, titles=titles)
        for obj in objects:
            obj.groups.add(group) 
Example #3
Source File: test_utils.py    From django-linguist with MIT License 5 votes vote down vote up
def test_get_language(self):
        # Full? Returns first level
        translation.activate("en-us")
        self.assertEqual(utils.get_language(), "en")

        # Unsupported? Returns fallback one
        translation.activate("ru")
        self.assertEqual(utils.get_fallback_language(), "en")
        self.assertEqual(utils.get_language(), utils.get_fallback_language())

        # Deactivating all should returns fallback one
        translation.deactivate_all()
        self.assertEqual(utils.get_fallback_language(), "en")
        self.assertEqual(utils.get_language(), utils.get_fallback_language()) 
Example #4
Source File: test_utils.py    From django-linguist with MIT License 5 votes vote down vote up
def test_build_localized_field_name(self):
        self.assertEqual(utils.build_localized_field_name("title", "fr"), "title_fr")
        self.assertEqual(
            utils.build_localized_field_name("title", "fr-ca"), "title_fr_ca"
        )

        translation.deactivate_all()
        self.assertEqual(utils.build_localized_field_name("title"), "title_en")

        translation.activate("it")
        self.assertEqual(utils.build_localized_field_name("title"), "title_it") 
Example #5
Source File: test_templatetags.py    From Inboxen with GNU Affero General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        translation.deactivate_all() 
Example #6
Source File: base.py    From GTDWeb with GNU General Public License v2.0 4 votes vote down vote up
def execute(self, *args, **options):
        """
        Try to execute this command, performing system checks if needed (as
        controlled by attributes ``self.requires_system_checks`` and
        ``self.requires_model_validation``, except if force-skipped).
        """
        if options.get('no_color'):
            self.style = no_style()
            self.stderr.style_func = None
        if options.get('stdout'):
            self.stdout = OutputWrapper(options['stdout'])
        if options.get('stderr'):
            self.stderr = OutputWrapper(options.get('stderr'), self.stderr.style_func)

        saved_locale = None
        if not self.leave_locale_alone:
            # Only mess with locales if we can assume we have a working
            # settings file, because django.utils.translation requires settings
            # (The final saying about whether the i18n machinery is active will be
            # found in the value of the USE_I18N setting)
            if not self.can_import_settings:
                raise CommandError("Incompatible values of 'leave_locale_alone' "
                                   "(%s) and 'can_import_settings' (%s) command "
                                   "options." % (self.leave_locale_alone,
                                                 self.can_import_settings))
            # Deactivate translations, because django-admin creates database
            # content like permissions, and those shouldn't contain any
            # translations.
            from django.utils import translation
            saved_locale = translation.get_language()
            translation.deactivate_all()

        try:
            if (self.requires_system_checks and
                    not options.get('skip_validation') and  # Remove at the end of deprecation for `skip_validation`.
                    not options.get('skip_checks')):
                self.check()
            output = self.handle(*args, **options)
            if output:
                if self.output_transaction:
                    # This needs to be imported here, because it relies on
                    # settings.
                    from django.db import connections, DEFAULT_DB_ALIAS
                    connection = connections[options.get('database', DEFAULT_DB_ALIAS)]
                    if connection.ops.start_transaction_sql():
                        self.stdout.write(self.style.SQL_KEYWORD(connection.ops.start_transaction_sql()))
                self.stdout.write(output)
                if self.output_transaction:
                    self.stdout.write('\n' + self.style.SQL_KEYWORD(connection.ops.end_transaction_sql()))
        finally:
            if saved_locale is not None:
                translation.activate(saved_locale) 
Example #7
Source File: test_expressions.py    From django-localized-fields with MIT License 4 votes vote down vote up
def test_localized_ref(cls):
        """Tests whether the :see:LocalizedRef expression properly works."""

        obj = cls.TestModel1.objects.create(name="bla bla")
        for i in range(0, 10):
            cls.TestModel2.objects.create(
                text=LocalizedValue(
                    dict(
                        en="text_%d_en" % i,
                        ro="text_%d_ro" % i,
                        nl="text_%d_nl" % i,
                    )
                ),
                other=obj,
            )

        def create_queryset(ref):
            return cls.TestModel1.objects.annotate(mytexts=ref).values_list(
                "mytexts", flat=True
            )

        # assert that it properly selects the currently active language
        for lang_code, _ in settings.LANGUAGES:
            translation.activate(lang_code)
            queryset = create_queryset(LocalizedRef("features__text"))

            for index, value in enumerate(queryset):
                assert translation.get_language() in value
                assert str(index) in value

        # ensure that the default language is used in case no
        # language is active at all
        translation.deactivate_all()
        queryset = create_queryset(LocalizedRef("features__text"))
        for index, value in enumerate(queryset):
            assert settings.LANGUAGE_CODE in value
            assert str(index) in value

        # ensures that overriding the language works properly
        queryset = create_queryset(LocalizedRef("features__text", "ro"))
        for index, value in enumerate(queryset):
            assert "ro" in value
            assert str(index) in value

        # ensures that using this in combination with ArrayAgg works properly
        queryset = create_queryset(
            ArrayAgg(LocalizedRef("features__text", "ro"))
        ).first()
        assert isinstance(queryset, list)
        for value in queryset:
            assert "ro" in value