Python django.conf.settings.LANGUAGES Examples

The following are 30 code examples of django.conf.settings.LANGUAGES(). 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.conf.settings , or try the search function .
Example #1
Source File: widgets.py    From django-localized-fields with 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 #2
Source File: i18n.py    From GTDWeb with 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
Source File: models.py    From linkedevents with 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 #4
Source File: city_sdk.py    From linkedevents with 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
Source File: test_bleach_field.py    From django-localized-fields with 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 #6
Source File: api.py    From linkedevents with 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
Source File: test_integer_field.py    From django-localized-fields with 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 #8
Source File: backends.py    From linkedevents with 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 #9
Source File: i18n.py    From GTDWeb with 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 #10
Source File: lippupiste.py    From linkedevents with 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 #11
Source File: test_slug_fields.py    From django-localized-fields with 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 #12
Source File: test_slug_fields.py    From django-localized-fields with 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 #13
Source File: i18n.py    From bioforum with 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 #14
Source File: integrations.py    From django-polaris with 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 #15
Source File: i18n.py    From bioforum with 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 #16
Source File: value.py    From django-localized-fields with 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 #17
Source File: forms.py    From django-localized-fields with 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 #18
Source File: signals.py    From online-judge with 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 #19
Source File: test_tags.py    From rdmo with 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 #20
Source File: integer_field.py    From django-localized-fields with 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 #21
Source File: autoslug_field.py    From django-localized-fields with 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 #22
Source File: factories.py    From pycon with 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 #23
Source File: test_file_field_form.py    From django-localized-fields with 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 #24
Source File: test_float_field.py    From django-localized-fields with 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 #25
Source File: test_float_field.py    From django-localized-fields with 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 #26
Source File: i18n.py    From GTDWeb with 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
Source File: field.py    From django-localized-fields with MIT License 5 votes vote down vote up
def clean(self, value, *_):
        """Cleans the specified value into something we can store in the
        database.

        For example, when all the language fields are
        left empty, and the field is allowed to be null,
        we will store None instead of empty keys.

        Arguments:
            value:
                The value to clean.

        Returns:
            The cleaned value, ready for database storage.
        """

        if not value or not isinstance(value, LocalizedValue):
            return None

        # are any of the language fiels None/empty?
        is_all_null = True
        for lang_code, _ in settings.LANGUAGES:
            if value.get(lang_code) is not None:
                is_all_null = False
                break

        # all fields have been left empty and we support
        # null values, let's return null to represent that
        if is_all_null and self.null:
            return None

        return value 
Example #28
Source File: test_integer_field.py    From django-localized-fields with MIT License 5 votes vote down vote up
def test_translate_primary_fallback(self):
        """Tests whether casting the value to an integer results in the value
        begin returned in the active language and falls back to the primary
        language if there is no value in that language."""

        obj = self.TestModel()
        obj.score.set(settings.LANGUAGE_CODE, 25)

        secondary_language = settings.LANGUAGES[-1][0]
        assert obj.score.get(secondary_language) is None

        with translation.override(secondary_language):
            assert obj.score.translate() == 25
            assert int(obj.score) == 25 
Example #29
Source File: test_integer_field.py    From django-localized-fields with MIT License 5 votes vote down vote up
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):
                assert int(obj.score) == index + 1
                assert obj.score.translate() == index + 1 
Example #30
Source File: test_file_field_form.py    From django-localized-fields with MIT License 5 votes vote down vote up
def test_bound_data(self):
        """Tests whether the :see:bound_data function is returns correctly
        value."""

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

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