Python django.conf.settings.LANGUAGES Examples

The following are 30 code examples for showing how to use django.conf.settings.LANGUAGES(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: GTDWeb   Author: lanbing510   File: i18n.py    License: GNU General Public License v2.0 6 votes vote down vote up
def do_get_available_languages(parser, token):
    """
    This will store a list of available languages
    in the context.

    Usage::

        {% get_available_languages as languages %}
        {% for language in languages %}
        ...
        {% endfor %}

    This will just pull the LANGUAGES setting from
    your setting file (or the default settings) and
    put it into the named variable.
    """
    # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
    args = token.contents.split()
    if len(args) != 3 or args[1] != 'as':
        raise TemplateSyntaxError("'get_available_languages' requires 'as variable' (got %r)" % args)
    return GetAvailableLanguagesNode(args[2]) 
Example 2
Project: GTDWeb   Author: lanbing510   File: i18n.py    License: GNU General Public License v2.0 6 votes vote down vote up
def do_get_language_info_list(parser, token):
    """
    This will store a list of language information dictionaries for the given
    language codes in a context variable. The language codes can be specified
    either as a list of strings or a settings.LANGUAGES style tuple (or any
    sequence of sequences whose first items are language codes).

    Usage::

        {% get_language_info_list for LANGUAGES as langs %}
        {% for l in langs %}
          {{ l.code }}
          {{ l.name }}
          {{ l.name_local }}
          {{ l.bidi|yesno:"bi-directional,uni-directional" }}
        {% endfor %}
    """
    args = token.split_contents()
    if len(args) != 5 or args[1] != 'for' or args[3] != 'as':
        raise TemplateSyntaxError("'%s' requires 'for sequence as variable' (got %r)" % (args[0], args[1:]))
    return GetLanguageInfoListNode(parser.compile_filter(args[2]), args[4]) 
Example 3
Project: linkedevents   Author: City-of-Helsinki   File: backends.py    License: MIT License 6 votes vote down vote up
def forward_to_backends(self, method, *args, **kwargs):
        # forwards the desired backend method to all the language backends
        initial_language = translation.get_language()
        # retrieve unique backend name
        backends = []
        for language, _ in settings.LANGUAGES:
            using = '%s-%s' % (self.connection_alias, language)
            # Ensure each backend is called only once
            if using in backends:
                continue
            else:
                backends.append(using)
            translation.activate(language)
            backend = connections[using].get_backend()
            getattr(backend.parent_class, method)(backend, *args, **kwargs)

        if initial_language is not None:
            translation.activate(initial_language)
        else:
            translation.deactivate() 
Example 4
Project: linkedevents   Author: City-of-Helsinki   File: city_sdk.py    License: MIT License 6 votes vote down vote up
def _generate_exportable_category(event):
        citysdk_category = dict()

        citysdk_category['author'] = CITYSDK_DEFAULT_AUTHOR
        citysdk_category['lang'] = bcp47_lang_map[settings.LANGUAGES[0][0]]
        citysdk_category['term'] = 'category'

        to_field_name = 'label'
        citysdk_category[to_field_name] = []
        for lang in [x[0] for x in settings.LANGUAGES]:
            value = getattr(event, '%s_%s' % ("name", lang))
            if value:
                lang_dict = {
                    'term': 'primary',
                    'value': value,
                    'lang': bcp47_lang_map[lang]
                }
                citysdk_category[to_field_name].append(lang_dict)

        return citysdk_category 
Example 5
Project: linkedevents   Author: City-of-Helsinki   File: models.py    License: MIT License 6 votes vote down vote up
def __str__(self):
        name = ''
        languages = [lang[0] for lang in settings.LANGUAGES]
        for lang in languages:
            lang = lang.replace('-', '_')  # to handle complex codes like e.g. zh-hans
            s = getattr(self, 'name_%s' % lang, None)
            if s:
                name = s
                break
        val = [name, '(%s)' % self.id]
        dcount = self.get_descendant_count()
        if dcount > 0:
            val.append(u" (%d children)" % dcount)
        else:
            val.append(str(self.start_time))
        return u" ".join(val) 
Example 6
Project: linkedevents   Author: City-of-Helsinki   File: api.py    License: MIT License 6 votes vote down vote up
def validate(self, data):
        if 'name' in self.translated_fields:
            name_exists = False
            languages = [x[0] for x in settings.LANGUAGES]
            for language in languages:
                # null or empty strings are not allowed, they are the same as missing name!
                if 'name_%s' % language in data and data['name_%s' % language]:
                    name_exists = True
                    break
        else:
            # null or empty strings are not allowed, they are the same as missing name!
            name_exists = 'name' in data and data['name']
        if not name_exists:
            raise serializers.ValidationError({'name': _('The name must be specified.')})
        super().validate(data)
        return data 
Example 7
Project: linkedevents   Author: City-of-Helsinki   File: lippupiste.py    License: MIT License 6 votes vote down vote up
def setup(self):
        self.languages_to_detect = [lang[0].replace('-', '_') for lang in settings.LANGUAGES
                                    if lang[0] not in self.supported_languages]
        ytj_data_source, _ = DataSource.objects.get_or_create(defaults={'name': "YTJ"}, id='ytj')
        parent_org_args = dict(origin_id='0586977-6', data_source=ytj_data_source)
        parent_defaults = dict(name='Helsinki Marketing Oy')
        self.parent_organization, _ = Organization.objects.get_or_create(
            defaults=parent_defaults, **parent_org_args)

        org_args = dict(origin_id='1789232-4', data_source=ytj_data_source, internal_type=Organization.AFFILIATED,
                        parent=self.parent_organization)
        org_defaults = dict(name="Lippupiste Oy")
        self.organization, _ = Organization.objects.get_or_create(defaults=org_defaults, **org_args)
        data_source_args = dict(id=self.name)
        data_source_defaults = dict(name="Lippupiste", owner=self.organization)
        self.data_source, _ = DataSource.objects.get_or_create(defaults=data_source_defaults, **data_source_args)
        self.tprek_data_source = DataSource.objects.get(id='tprek')
        self._cache_yso_keyword_objects()
        self._cache_place_data()
        try:
            self.event_only_license = License.objects.get(id='event_only')
        except License.DoesNotExist:
            self.event_only_license = None

        self.sub_event_count_by_super_event_source_id = defaultdict(lambda: 0) 
Example 8
Project: bioforum   Author: reBiocoder   File: i18n.py    License: MIT License 6 votes vote down vote up
def do_get_available_languages(parser, token):
    """
    This will store a list of available languages
    in the context.

    Usage::

        {% get_available_languages as languages %}
        {% for language in languages %}
        ...
        {% endfor %}

    This will just pull the LANGUAGES setting from
    your setting file (or the default settings) and
    put it into the named variable.
    """
    # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
    args = token.contents.split()
    if len(args) != 3 or args[1] != 'as':
        raise TemplateSyntaxError("'get_available_languages' requires 'as variable' (got %r)" % args)
    return GetAvailableLanguagesNode(args[2]) 
Example 9
Project: bioforum   Author: reBiocoder   File: i18n.py    License: MIT License 6 votes vote down vote up
def do_get_language_info_list(parser, token):
    """
    This will store a list of language information dictionaries for the given
    language codes in a context variable. The language codes can be specified
    either as a list of strings or a settings.LANGUAGES style list (or any
    sequence of sequences whose first items are language codes).

    Usage::

        {% get_language_info_list for LANGUAGES as langs %}
        {% for l in langs %}
          {{ l.code }}
          {{ l.name }}
          {{ l.name_translated }}
          {{ l.name_local }}
          {{ l.bidi|yesno:"bi-directional,uni-directional" }}
        {% endfor %}
    """
    args = token.split_contents()
    if len(args) != 5 or args[1] != 'for' or args[3] != 'as':
        raise TemplateSyntaxError("'%s' requires 'for sequence as variable' (got %r)" % (args[0], args[1:]))
    return GetLanguageInfoListNode(parser.compile_filter(args[2]), args[4]) 
Example 10
Project: django-polaris   Author: stellar   File: integrations.py    License: Apache License 2.0 6 votes vote down vote up
def info_integration(asset: Asset, lang: str):
    # Not using `asset` since this reference server only supports SRT
    languages = [l[0] for l in server_settings.LANGUAGES]
    if lang and lang not in languages:
        raise ValueError()
    return {
        "fields": {
            "type": {
                "description": _("'bank_account' is the only value supported'"),
                "choices": ["bank_account"],
            },
        },
        "types": {
            "bank_account": {
                "fields": {
                    "dest": {"description": _("bank account number")},
                    "dest_extra": {"description": _("bank routing number")},
                }
            }
        },
    } 
Example 11
Project: pycon   Author: pythonitalia   File: factories.py    License: MIT License 6 votes vote down vote up
def languages(self, create, extracted, **kwargs):
        """Accepts a list of language codes and adds each language to the
        Conference allowed languages.

        This fixture makes easier to add allowed languages to a Conference in the tests
        """
        if not create:
            return

        if extracted:
            for language_code in extracted:
                self.languages.add(Language.objects.get(code=language_code))
        else:
            self.languages.add(
                Language.objects.get(code=random.choice(settings.LANGUAGES)[0])
            ) 
Example 12
Project: rdmo   Author: rdmorganiser   File: test_tags.py    License: Apache License 2.0 6 votes vote down vote up
def test_i18n_switcher(rf):
    """ The language switcher is rendered correctly. """

    # create a fake template with a name
    template = "{% load core_tags %}{% i18n_switcher %}"

    # set a language
    translation.activate(settings.LANGUAGES[0][0])

    # render the link
    request = rf.get(reverse('home'))
    context = RequestContext(request, {})
    rendered_template = Template(template).render(context)
    for language in settings.LANGUAGES:
        if language == settings.LANGUAGES[0]:
            assert '<a href="/i18n/%s/"><u>%s</u></a>' % language in rendered_template
        else:
            assert'<a href="/i18n/%s/">%s</a>' % language in rendered_template 
Example 13
Project: online-judge   Author: DMOJ   File: signals.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def problem_update(sender, instance, **kwargs):
    if hasattr(instance, '_updating_stats_only'):
        return

    cache.delete_many([
        make_template_fragment_key('submission_problem', (instance.id,)),
        make_template_fragment_key('problem_feed', (instance.id,)),
        'problem_tls:%s' % instance.id, 'problem_mls:%s' % instance.id,
    ])
    cache.delete_many([make_template_fragment_key('problem_html', (instance.id, engine, lang))
                       for lang, _ in settings.LANGUAGES for engine in EFFECTIVE_MATH_ENGINES])
    cache.delete_many([make_template_fragment_key('problem_authors', (instance.id, lang))
                       for lang, _ in settings.LANGUAGES])
    cache.delete_many(['generated-meta-problem:%s:%d' % (lang, instance.id) for lang, _ in settings.LANGUAGES])

    for lang, _ in settings.LANGUAGES:
        unlink_if_exists(get_pdf_path('%s.%s.pdf' % (instance.code, lang))) 
Example 14
Project: django-localized-fields   Author: SectorLabs   File: widgets.py    License: MIT License 6 votes vote down vote up
def decompress(self, value: LocalizedValue) -> List[str]:
        """Decompresses the specified value so it can be spread over the
        internal widgets.

        Arguments:
            value:
                The :see:LocalizedValue to display in this
                widget.

        Returns:
            All values to display in the inner widgets.
        """

        result = []
        for lang_code, _ in settings.LANGUAGES:
            if value:
                result.append(value.get(lang_code))
            else:
                result.append(None)

        return result 
Example 15
Project: django-localized-fields   Author: SectorLabs   File: value.py    License: MIT License 6 votes vote down vote up
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 
Example 16
Project: django-localized-fields   Author: SectorLabs   File: forms.py    License: MIT License 6 votes vote down vote up
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_class()

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

        return localized_value 
Example 17
Project: django-localized-fields   Author: SectorLabs   File: integer_field.py    License: MIT License 6 votes vote down vote up
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) 
Example 18
Project: django-localized-fields   Author: SectorLabs   File: autoslug_field.py    License: MIT License 6 votes vote down vote up
def _get_populate_values(self, instance) -> Tuple[str, str]:
        """Gets all values (for each language) from the specified's instance's
        `populate_from` field.

        Arguments:
            instance:
                The instance to get the values from.

        Returns:
            A list of (lang_code, value) tuples.
        """

        return [
            (
                lang_code,
                self._get_populate_from_value(
                    instance, self.populate_from, lang_code
                ),
            )
            for lang_code, _ in settings.LANGUAGES
        ] 
Example 19
Project: django-localized-fields   Author: SectorLabs   File: test_file_field_form.py    License: MIT License 6 votes vote down vote up
def test_clean(self):
        """Tests whether the :see:clean function is working properly."""

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

        formfield = LocalizedFileFieldForm(required=False)
        formfield.clean([""] * len(settings.LANGUAGES))
        formfield.clean(["", ""], ["", ""]) 
Example 20
Project: django-localized-fields   Author: SectorLabs   File: test_float_field.py    License: MIT License 6 votes vote down vote up
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.assertRaises(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.assertRaises(IntegrityError):
            obj = self.TestModel()
            for lang_code, _ in settings.LANGUAGES:
                if lang_code == settings.LANGUAGE_CODE:
                    continue
                obj.score.set(lang_code, 23.0)
            obj.save() 
Example 21
Project: django-localized-fields   Author: SectorLabs   File: test_float_field.py    License: MIT License 6 votes vote down vote up
def test_default_value(self):
        """Tests whether a default is properly set when specified."""

        model = get_fake_model(
            {
                "score": LocalizedFloatField(
                    default={settings.LANGUAGE_CODE: 75.0}
                )
            }
        )

        obj = model.objects.create()
        assert obj.score.get(settings.LANGUAGE_CODE) == 75.0

        obj = model()
        for lang_code, _ in settings.LANGUAGES:
            obj.score.set(lang_code, None)
        obj.save()

        for lang_code, _ in settings.LANGUAGES:
            if lang_code == settings.LANGUAGE_CODE:
                assert obj.score.get(lang_code) == 75.0
            else:
                assert obj.score.get(lang_code) is None 
Example 22
Project: django-localized-fields   Author: SectorLabs   File: test_slug_fields.py    License: MIT License 6 votes vote down vote up
def test_populate_callable(cls):
        """Tests whether the populating feature works correctly when you
        specify a callable."""

        def generate_slug(instance):
            return instance.title

        get_fake_model(
            {
                "title": LocalizedField(),
                "slug": LocalizedUniqueSlugField(populate_from=generate_slug),
            }
        )

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

        obj.save()

        for lang_code, lang_name in settings.LANGUAGES:
            assert obj.slug.get(lang_code) == "title-%s" % lang_name.lower() 
Example 23
Project: django-localized-fields   Author: SectorLabs   File: test_slug_fields.py    License: MIT License 6 votes vote down vote up
def test_populate_multiple_from_fields():
        """Tests whether populating the slug from multiple fields works
        correctly."""

        model = get_fake_model(
            {
                "title": LocalizedField(),
                "name": models.CharField(max_length=255),
                "slug": LocalizedUniqueSlugField(
                    populate_from=("title", "name")
                ),
            }
        )

        obj = model()
        for lang_code, lang_name in settings.LANGUAGES:
            obj.name = "swen"
            obj.title.set(lang_code, "title %s" % lang_name)

        obj.save()

        for lang_code, lang_name in settings.LANGUAGES:
            assert (
                obj.slug.get(lang_code) == "title-%s-swen" % lang_name.lower()
            ) 
Example 24
Project: django-localized-fields   Author: SectorLabs   File: test_bleach_field.py    License: MIT License 6 votes vote down vote up
def _validate(non_bleached_value, bleached_value):
        """Validates whether the specified non-bleached value ended up being
        correctly bleached.

        Arguments:
            non_bleached_value:
                The value before bleaching.

            bleached_value:
                The value after bleaching.
        """

        for lang_code, _ in settings.LANGUAGES:
            if not non_bleached_value.get(lang_code):
                assert not bleached_value.get(lang_code)
                continue

            expected_value = bleach.clean(
                non_bleached_value.get(lang_code), get_bleach_default_options()
            )

            assert bleached_value.get(lang_code) == expected_value 
Example 25
Project: django-localized-fields   Author: SectorLabs   File: test_integer_field.py    License: MIT License 6 votes vote down vote up
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.assertRaises(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.assertRaises(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() 
Example 26
Project: GTDWeb   Author: lanbing510   File: i18n.py    License: GNU General Public License v2.0 5 votes vote down vote up
def render(self, context):
        context[self.variable] = [(k, translation.ugettext(v)) for k, v in settings.LANGUAGES]
        return '' 
Example 27
Project: GTDWeb   Author: lanbing510   File: trans_real.py    License: GNU General Public License v2.0 5 votes vote down vote up
def reset_cache(**kwargs):
    """
    Reset global state when LANGUAGES setting has been changed, as some
    languages should no longer be accepted.
    """
    if kwargs['setting'] in ('LANGUAGES', 'LANGUAGE_CODE'):
        check_for_language.cache_clear()
        get_languages.cache_clear()
        get_supported_language_variant.cache_clear() 
Example 28
Project: GTDWeb   Author: lanbing510   File: trans_real.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_languages():
    """
    Cache of settings.LANGUAGES in an OrderedDict for easy lookups by key.
    """
    return OrderedDict(settings.LANGUAGES) 
Example 29
Project: GTDWeb   Author: lanbing510   File: context_processors.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 
Example 30
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_urls(self, page=1, site=None, protocol=None):
        # Determine protocol
        if self.protocol is not None:
            protocol = self.protocol
        if protocol is None:
            protocol = 'http'

        # Determine domain
        if site is None:
            if django_apps.is_installed('django.contrib.sites'):
                Site = django_apps.get_model('sites.Site')
                try:
                    site = Site.objects.get_current()
                except Site.DoesNotExist:
                    pass
            if site is None:
                raise ImproperlyConfigured(
                    "To use sitemaps, either enable the sites framework or pass "
                    "a Site/RequestSite object in your view."
                )
        domain = site.domain

        if getattr(self, 'i18n', False):
            urls = []
            current_lang_code = translation.get_language()
            for lang_code, lang_name in settings.LANGUAGES:
                translation.activate(lang_code)
                urls += self._urls(page, protocol, domain)
            translation.activate(current_lang_code)
        else:
            urls = self._urls(page, protocol, domain)

        return urls