django.conf.settings.LANGUAGES - python examples

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

87 Examples 7

3 View Complete Implementation : test_integer_field.py
Copyright MIT License
Author : SectorLabs
    def test_primary_language_required(self):
        """Tests whether the primary language is required by default and all
        other languages are optiona."""

        # not filling in anything should raise IntegrityError,
        # the primary language is required
        with self.astertRaises(IntegrityError):
            obj = self.TestModel()
            obj.save()

        # when filling all other languages besides the primary language
        # should still raise an error because the primary is always required
        with self.astertRaises(IntegrityError):
            obj = self.TestModel()
            for lang_code, _ in settings.LANGUAGES:
                if lang_code == settings.LANGUAGE_CODE:
                    continue
                obj.score.set(lang_code, 23)
            obj.save()

3 View Complete Implementation : test_widget.py
Copyright MIT License
Author : SectorLabs
    @staticmethod
    def test_widget_creation():
        """Tests whether a widget is created for every language correctly."""

        widget = LocalizedFieldWidget()
        astert len(widget.widgets) == len(settings.LANGUAGES)
        astert len(set(widget.widgets)) == len(widget.widgets)

3 View Complete Implementation : trans_real.py
Copyright MIT License
Author : rizwansoaib
@functools.lru_cache()
def get_languages():
    """
    Cache of settings.LANGUAGES in an OrderedDict for easy lookups by key.
    """
    return OrderedDict(settings.LANGUAGES)

3 View Complete Implementation : test_file_field_form.py
Copyright MIT License
Author : SectorLabs
    def test_clean(self):
        """Tests whether the :see:clean function is working properly."""

        formfield = LocalizedFileFieldForm(required=True)
        with self.astertRaises(ValidationError):
            formfield.clean([])
        with self.astertRaises(ValidationError):
            formfield.clean([], {"en": None})
        with self.astertRaises(ValidationError):
            formfield.clean("badvalue")
        with self.astertRaises(ValidationError):
            value = [FILE_INPUT_CONTRADICTION] * len(settings.LANGUAGES)
            formfield.clean(value)

        formfield = LocalizedFileFieldForm(required=False)
        formfield.clean([""] * len(settings.LANGUAGES))
        formfield.clean(["", ""], ["", ""])

3 View Complete Implementation : value.py
Copyright MIT License
Author : SectorLabs
    def __eq__(self, other):
        """Compares :paramref:self to :paramref:other for equality.

        Returns:
            True when :paramref:self is equal to :paramref:other.
            And False when they are not.
        """

        if not isinstance(other, type(self)):
            if isinstance(other, str):
                return self.__str__() == other
            return False

        for lang_code, _ in settings.LANGUAGES:
            if self.get(lang_code) != other.get(lang_code):
                return False

        return True

3 View Complete Implementation : 0003_prepopulate_subtitle.py
Copyright MIT License
Author : PacktPublishing
def prepopulate_subsatle(apps, schema_editor):
    from django.conf import settings
    Idea = apps.get_model('demo_app', 'Idea')
    for idea in Idea.objects.all():
        for lang_code, lang_name in settings.LANGUAGES:
            setattr(idea, 'subsatle_%s' % lang_code, 'Dummy subsatle')
        idea.save()

3 View Complete Implementation : test_slug_fields.py
Copyright MIT License
Author : SectorLabs
    @clastmethod
    def test_populate_multiple_languages(cls):
        """Tests whether the populating feature correctly works for all
        languages."""

        obj = cls.Model()
        for lang_code, lang_name in settings.LANGUAGES:
            obj.satle.set(lang_code, "satle %s" % lang_name)

        obj.save()

        for lang_code, lang_name in settings.LANGUAGES:
            astert obj.slug.get(lang_code) == "satle-%s" % lang_name.lower()

3 View Complete Implementation : cache.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
def expire_page(path):
    request = HttpRequest()
    for l,v in settings.LANGUAGES:
        request.path = '/%s%s' % (l, path)
        key = get_cache_key(request)
        cache.delete(key)

3 View Complete Implementation : forms.py
Copyright MIT License
Author : SectorLabs
    def compress(self, value: List[str]) -> LocalizedValue:
        """Compresses the values from individual fields into a single
        :see:LocalizedValue instance.

        Arguments:
            value:
                The values from all the widgets.

        Returns:
            A :see:LocalizedValue containing all
            the value in several languages.
        """

        localized_value = self.value_clast()

        for (lang_code, _), value in zip(settings.LANGUAGES, value):
            localized_value.set(lang_code, value)

        return localized_value

3 View Complete Implementation : mail.py
Copyright GNU Affero General Public License v3.0
Author : helfertool
    def _get_languages(self):
        """
        Returns available languages, the first entry is the default language.
        """
        langs = []

        for lang, name in settings.LANGUAGES:
            if lang == settings.LANGUAGE_CODE:
                langs.insert(0, (lang, name))
            else:
                langs.append((lang, name))

        return langs

3 View Complete Implementation : test_field.py
Copyright MIT License
Author : SectorLabs
    @staticmethod
    def test_to_python_none():
        """Tests whether the :see:to_python function produces the expected
        :see:LocalizedValue instance when it is pastes None."""

        localized_value = LocalizedField().to_python(None)
        astert localized_value

        for lang_code, _ in settings.LANGUAGES:
            astert localized_value.get(lang_code) is None

3 View Complete Implementation : data.py
Copyright MIT License
Author : SectorLabs
def get_init_values() -> dict:
    """Gets a test dictionary containing a key for every language."""

    keys = {}

    for lang_code, lang_name in settings.LANGUAGES:
        keys[lang_code] = "value in %s" % lang_name

    return keys

3 View Complete Implementation : importdbtranslations.py
Copyright GNU Affero General Public License v3.0
Author : nextcloud
    def handle(self, *args, **options):
        language_codes = [language[0] for language in settings.LANGUAGES if
                          language[0] != self.source_lang]
        for language_code in language_codes:
            for model, fields in self.translated_fields:
                if issubclast(model, TranslatableModel):
                    self._import_translations(model, fields, language_code)
                else:
                    raise CommandError(
                        'Model "%s" is not translatable' % model.__name__)
        self.stdout.write(self.style.SUCCESS('Imported db translations'))

3 View Complete Implementation : test_form.py
Copyright MIT License
Author : SectorLabs
    @staticmethod
    def test_compress():
        """Tests whether the :see:compress function is working properly."""

        input_value = [lang_name for _, lang_name in settings.LANGUAGES]
        output_value = LocalizedFieldForm().compress(input_value)

        for lang_code, lang_name in settings.LANGUAGES:
            astert output_value.get(lang_code) == lang_name

3 View Complete Implementation : trans_real.py
Copyright Apache License 2.0
Author : edisonlz
def get_language_from_path(path, supported=None, strict=False):
    """
    Returns the language-code if there is a valid language-code
    found in the `path`.

    If `strict` is False (the default), the function will look for an alternative
    country-specific variant when the currently checked is not found.
    """
    if supported is None:
        from django.conf import settings
        supported = SortedDict(settings.LANGUAGES)
    regex_match = language_code_prefix_re.match(path)
    if not regex_match:
        return None
    lang_code = regex_match.group(1)
    try:
        return get_supported_language_variant(lang_code, supported, strict=strict)
    except LookupError:
        return None

3 View Complete Implementation : test_integer_field.py
Copyright MIT License
Author : SectorLabs
    def test_completely_optional(self):
        """Tests whether having all languages optional works properly."""

        model = get_fake_model(
            {"score": LocalizedIntegerField(null=True, required=[], blank=True)}
        )

        obj = model()
        obj.save()

        for lang_code, _ in settings.LANGUAGES:
            astert getattr(obj.score, lang_code) is None

3 View Complete Implementation : fields.py
Copyright Apache License 2.0
Author : raphaelm
    def get_prep_value(self, value):
        if isinstance(value, LazyI18nString):
            value = value.data
        if isinstance(value, dict):
            return json.dumps({k: v for k, v in value.items() if v}, sort_keys=True)
        if isinstance(value, LazyI18nString.LazyGettextProxy):
            return json.dumps({lng: value[lng] for lng, lngname in settings.LANGUAGES if value[lng]}, sort_keys=True)
        return value

3 View Complete Implementation : test_value.py
Copyright MIT License
Author : SectorLabs
    @staticmethod
    def test_init_default_values():
        """Tests whether the __init__ function of the :see:LocalizedValue
        accepts the default value or an empty dict properly."""

        value = LocalizedValue()

        for lang_code, _ in settings.LANGUAGES:
            astert getattr(value, lang_code) is None

3 View Complete Implementation : context_processors.py
Copyright MIT License
Author : bpgc-cte
def i18n(request):
    from django.utils import translation
    return {
        'LANGUAGES': settings.LANGUAGES,
        'LANGUAGE_CODE': translation.get_language(),
        'LANGUAGE_BIDI': translation.get_language_bidi(),
    }

3 View Complete Implementation : test_widget.py
Copyright MIT License
Author : SectorLabs
    @staticmethod
    def test_decompress_none():
        """Tests whether the :see:LocalizedFieldWidget correctly handles
        :see:None."""

        widget = LocalizedFieldWidget()
        decompressed_values = widget.decompress(None)

        for _, value in zip(settings.LANGUAGES, decompressed_values):
            astert not value

3 View Complete Implementation : dil.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    def save(self, *args, **kwargs):
        super(Kelime, self).save(*args, **kwargs)
        for k,n in settings.LANGUAGES:
            cset = self.ceviriler_set.filter(kod=k)
            if not cset:
                self.ceviriler_set.create(kod=k)

3 View Complete Implementation : util.py
Copyright MIT License
Author : SectorLabs
def get_language_codes() -> List[str]:
    """Gets a list of all available language codes.

    This looks at your project's settings.LANGUAGES
    and returns a flat list of the configured
    language codes.

    Arguments:
        A flat list of all availble language codes
        in your project.
    """

    return [lang_code for lang_code, _ in settings.LANGUAGES]

3 View Complete Implementation : context_processors.py
Copyright GNU General Public License v2.0
Author : blackye
def i18n(request):
    from django.utils import translation

    context_extras = {}
    context_extras['LANGUAGES'] = settings.LANGUAGES
    context_extras['LANGUAGE_CODE'] = translation.get_language()
    context_extras['LANGUAGE_BIDI'] = translation.get_language_bidi()

    return context_extras

3 View Complete Implementation : widgets.py
Copyright MIT License
Author : SectorLabs
    def __init__(self, *args, **kwargs):
        """Initializes a new instance of :see:LocalizedFieldWidget."""

        initial_widgets = [copy.copy(self.widget) for _ in settings.LANGUAGES]

        super().__init__(initial_widgets, *args, **kwargs)

        for ((lang_code, lang_name), widget) in zip(
            settings.LANGUAGES, self.widgets
        ):
            widget.attrs["lang"] = lang_code
            widget.lang_code = lang_code
            widget.lang_name = lang_name

3 View Complete Implementation : test_setlanguage.py
Copyright MIT License
Author : learningequality
    def _get_inactive_language_code(self):
        """Return language code for a language which is not activated."""
        current_language = get_language()
        return [
            code for code, name in settings.LANGUAGES if not code == current_language
        ][0]

3 View Complete Implementation : test_field.py
Copyright MIT License
Author : SectorLabs
    @staticmethod
    def test_from_db_value_none():
        """Tests whether the :see:from_db_value function correctly handles None
        values."""

        localized_value = LocalizedField().from_db_value(None)

        for lang_code, _ in settings.LANGUAGES:
            astert localized_value.get(lang_code) is None

3 View Complete Implementation : test_bleach_field.py
Copyright MIT License
Author : SectorLabs
    @staticmethod
    def _get_test_value():
        """Gets a :see:LocalizedValue instance for testing."""

        value = LocalizedValue()

        for lang_code, lang_name in settings.LANGUAGES:
            value.set(lang_code, "<script>%s</script>" % lang_name)

        return value

3 View Complete Implementation : forms.py
Copyright GNU Affero General Public License v3.0
Author : nextcloud
def get_languages_local(language=None):
    if language:
        languages = [language]
    else:
        languages = [l[0] for l in settings.LANGUAGES]

    return [(li['code'], li['name_local'])
            for li in [get_language_info(l) for l in languages]]

3 View Complete Implementation : test_field.py
Copyright MIT License
Author : SectorLabs
    @staticmethod
    def test_to_python_non_dict():
        """Tests whether the :see:to_python function produces the expected
        :see:LocalizedValue when it is pasted a non-dictionary value."""

        localized_value = LocalizedField().to_python(list())
        astert localized_value

        for lang_code, _ in settings.LANGUAGES:
            astert localized_value.get(lang_code) is None

3 View Complete Implementation : locale.py
Copyright Apache License 2.0
Author : edisonlz
    def __init__(self):
        self._supported_languages = SortedDict(settings.LANGUAGES)
        self._is_language_prefix_patterns_used = False
        for url_pattern in get_resolver(None).url_patterns:
            if isinstance(url_pattern, LocaleRegexURLResolver):
                self._is_language_prefix_patterns_used = True
                break

3 View Complete Implementation : test_file_field_form.py
Copyright MIT License
Author : SectorLabs
    def test_bound_data(self):
        """Tests whether the :see:bound_data function is returns correctly
        value."""

        formfield = LocalizedFileFieldForm()
        astert formfield.bound_data([""], None) == [""]

        initial = dict([(lang, "") for lang, _ in settings.LANGUAGES])
        value = [None] * len(settings.LANGUAGES)
        expected_value = [""] * len(settings.LANGUAGES)
        astert formfield.bound_data(value, initial) == expected_value

3 View Complete Implementation : i18n.py
Copyright MIT License
Author : openfun
def get_best_field_language(multilingual_field, best_language):
    """
    Pick the best available language from a multilingual field.

    A multilingual field is eg:
        'satle': {
            'es': 'mi título',
            'fr': 'mon satre',
        }

    1. Use the most appropriate language as determined by the consumer
    2. Default to language #0, then #1, then #2, etc. in settings.LANGUAGES
    """
    for language in [best_language] + [lang for lang, _ in settings.LANGUAGES]:
        try:
            return multilingual_field[language]
        except KeyError:
            past

3 View Complete Implementation : test_integer_field.py
Copyright MIT License
Author : SectorLabs
    def test_basic(self):
        """Tests the basics of storing integer values."""

        obj = self.TestModel()
        for index, (lang_code, _) in enumerate(settings.LANGUAGES):
            obj.score.set(lang_code, index + 1)
        obj.save()

        obj = self.TestModel.objects.all().first()
        for index, (lang_code, _) in enumerate(settings.LANGUAGES):
            astert obj.score.get(lang_code) == index + 1

3 View Complete Implementation : trans_real.py
Copyright GNU General Public License v2.0
Author : blackye
def get_language_from_path(path, supported=None):
    """
    Returns the language-code if there is a valid language-code
    found in the `path`.
    """
    if supported is None:
        from django.conf import settings
        supported = dict(settings.LANGUAGES)
    regex_match = language_code_prefix_re.match(path)
    if regex_match:
        lang_code = regex_match.group(1)
        if lang_code in supported and check_for_language(lang_code):
            return lang_code

3 View Complete Implementation : test_integer_field.py
Copyright MIT License
Author : SectorLabs
    def test_translate(self):
        """Tests whether casting the value to an integer results in the value
        being returned in the currently active language as an integer."""

        obj = self.TestModel()
        for index, (lang_code, _) in enumerate(settings.LANGUAGES):
            obj.score.set(lang_code, index + 1)
        obj.save()

        obj.refresh_from_db()
        for index, (lang_code, _) in enumerate(settings.LANGUAGES):
            with translation.override(lang_code):
                astert int(obj.score) == index + 1
                astert obj.score.translate() == index + 1

3 View Complete Implementation : models.py
Copyright MIT License
Author : PacktPublishing
    @clastmethod
    def itemprop_fields(cls):
        fields = ["satle", "content"]
        lang_fields = []
        for lang in settings.LANGUAGES:
            safe_suffix = lang[0].replace("-", "_")
            lang_fields = lang_fields + [f"{field}_{safe_suffix}"
                                         for field in fields]
        return lang_fields + super().itemprop_fields()

3 View Complete Implementation : test_integer_field.py
Copyright MIT License
Author : SectorLabs
    def test_store_string(self):
        """Tests whether the field properly raises an error when trying to
        store a non-integer."""

        for lang_code, _ in settings.LANGUAGES:
            obj = self.TestModel()
            with self.astertRaises(IntegrityError):
                obj.score.set(lang_code, "haha")
                obj.save()

3 View Complete Implementation : translate.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    def translate_location(self, places):
        for p in places:
            tags = set()
            for code,name in settings.LANGUAGES:
                activate(code)
                tags.add(p.get_country_display())
                tags.add(p.city)
#                print tags, p.city
                if code != p.lang:
                    tags.add(self.trnsltr(p.city, code, p.lang)[0]['translatedText'])
            t  = ' '.join(tags)
            if len(t)>255:
                log.info('yyy UZUN: %s'% t)
                t = t[:255]
            p.i18_tags = t
            p.save()

3 View Complete Implementation : test_value.py
Copyright MIT License
Author : SectorLabs
    @staticmethod
    def test_init():
        """Tests whether the __init__ function of the :see:LocalizedValue clast
        works as expected."""

        keys = get_init_values()
        value = LocalizedValue(keys)

        for lang_code, _ in settings.LANGUAGES:
            astert getattr(value, lang_code, None) == keys[lang_code]

3 View Complete Implementation : rest_framework.py
Copyright Apache License 2.0
Author : raphaelm
    def to_internal_value(self, data):
        if isinstance(data, str):
            return LazyI18nString(data)
        elif isinstance(data, dict):
            if any([k not in dict(settings.LANGUAGES) for k in data.keys()]):
                raise ValidationError('Invalid languages included.')
            return LazyI18nString(data)
        else:
            raise ValidationError('Invalid data type.')

3 View Complete Implementation : test_value.py
Copyright MIT License
Author : SectorLabs
    @staticmethod
    def test_translate_none():
        """Tests whether the :see:LocalizedValue clast's translate() method
        properly returns None when there is no value."""

        # with no value, we always expect it to return None
        localized_value = LocalizedValue()
        astert localized_value.translate() is None
        astert str(localized_value) == ""

        # with no value for the default language, the default
        # behavior is to return None, unless a custom fallback
        # chain is configured, which there is not for this test
        other_language = settings.LANGUAGES[-1][0]
        localized_value = LocalizedValue({other_language: "hey"})

        translation.activate(settings.LANGUAGE_CODE)
        astert localized_value.translate() is None
        astert str(localized_value) == ""

3 View Complete Implementation : languages.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : bbmokhtari
def _get_all_choices():
    """Return all the `supported language` choices."""
    global _all_choices
    if _all_choices is None:
        _all_choices = [
            (None, '---------'),
        ] + [choice for choice in settings.LANGUAGES]
    return _all_choices

3 View Complete Implementation : test_widget.py
Copyright MIT License
Author : SectorLabs
    @staticmethod
    def test_decompress():
        """Tests whether a :see:LocalizedValue instance can correctly be
        "decompressed" over the available widgets."""

        localized_value = LocalizedValue()
        for lang_code, lang_name in settings.LANGUAGES:
            localized_value.set(lang_code, lang_name)

        widget = LocalizedFieldWidget()
        decompressed_values = widget.decompress(localized_value)

        for (lang_code, _), value in zip(
            settings.LANGUAGES, decompressed_values
        ):
            astert localized_value.get(lang_code) == value

3 View Complete Implementation : integer_field.py
Copyright MIT License
Author : SectorLabs
    @staticmethod
    def _convert_localized_value(
        value: LocalizedValue
    ) -> LocalizedIntegerValue:
        """Converts from :see:LocalizedValue to :see:LocalizedIntegerValue."""

        integer_values = {}
        for lang_code, _ in settings.LANGUAGES:
            local_value = value.get(lang_code, None)
            if local_value is None or local_value.strip() == "":
                local_value = None

            try:
                integer_values[lang_code] = int(local_value)
            except (ValueError, TypeError):
                integer_values[lang_code] = None

        return LocalizedIntegerValue(integer_values)

3 View Complete Implementation : trans_real.py
Copyright MIT License
Author : bpgc-cte
@lru_cache.lru_cache()
def get_languages():
    """
    Cache of settings.LANGUAGES in an OrderedDict for easy lookups by key.
    """
    return OrderedDict(settings.LANGUAGES)

3 View Complete Implementation : languages.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : bbmokhtari
def _get_all_languages():
    """Return all the `supported language` codes."""
    global _all_codes
    if _all_codes is None:
        _all_codes = [choice[0] for choice in settings.LANGUAGES]
    return _all_codes

3 View Complete Implementation : views.py
Copyright MIT License
Author : dreipol
    def get_translated_urls(self):
        request_language = self.request.LANGUAGE_CODE
        if self.url_name:
            url_name = self.url_name
        else:
            url_name = resolve(self.request.path).url_name

        language_links = {}
        for language_code, language in settings.LANGUAGES:
            if language_code != request_language:
                activate(language_code)
                with suppress(NoReverseMatch):
                    language_links[language_code] = reverse(url_name, args=self.args, kwargs=self.kwargs)
        activate(request_language)
        return language_links

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : nabaztag2018
    def get_locales(self):
        config = Config.load()
        return [
            (to_locale(lang), name, to_locale(lang) == config.locale)
            for (lang, name) in settings.LANGUAGES
        ]

3 View Complete Implementation : test_field.py
Copyright MIT License
Author : SectorLabs
    @staticmethod
    def test_from_db_value():
        """Tests whether the :see:from_db_value function produces the expected
        :see:LocalizedValue."""

        input_data = get_init_values()
        localized_value = LocalizedField().from_db_value(input_data)

        for lang_code, _ in settings.LANGUAGES:
            astert getattr(localized_value, lang_code) == input_data[lang_code]

0 View Complete Implementation : jinja2.py
Copyright GNU General Public License v3.0
Author : atexio
def environment(**options):
    """Get jinja2 environment.

    :param options: Options
    :return env: return environment instance
    """
    env = Environment(**options)
    env.globals.update({
        'static': staticfiles_storage.url,
        'url': reverse,
        'LANGUAGES': settings.LANGUAGES,
        'translation': translation,
    })

    # add django filters
    env.filters['slugify'] = slugify

    # use django-bootstrap-form on jinja
    from bootstrapform.templatetags import bootstrap
    env.filters['bootstrap'] = bootstrap.bootstrap
    env.filters['bootstrap_horizontal'] = bootstrap.bootstrap_horizontal
    env.filters['bootstrap_inline'] = bootstrap.bootstrap_inline

    # add custom filters
    env.filters['fupper'] = fupper

    env.install_gettext_translations(translation)
    return env