Python django.conf.settings.LANGUAGE_CODE Examples

The following are 30 code examples of django.conf.settings.LANGUAGE_CODE(). 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: classified.py    From django-classified with MIT License 6 votes vote down vote up
def currency(value, currency=None):
    """
    Format decimal value as currency
    """
    try:
        value = D(value)
    except (TypeError, InvalidOperation):
        return ""

    # Using Babel's currency formatting
    # http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency

    kwargs = {
        'currency': currency or CURRENCY,
        'locale': to_locale(get_language() or settings.LANGUAGE_CODE)
    }

    return format_currency(value, **kwargs) 
Example #2
Source File: test_integer_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": LocalizedIntegerField(
                    default={settings.LANGUAGE_CODE: 75}
                )
            }
        )

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

        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
            else:
                assert obj.score.get(lang_code) is None 
Example #3
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 #4
Source File: value.py    From django-localized-fields with MIT License 6 votes vote down vote up
def get(self, language: str = None, default: str = None) -> str:
        """Gets the underlying value in the specified or primary language.

        Arguments:
            language:
                The language to get the value in.

        Returns:
            The value in the current language, or
            the primary language in case no language
            was specified.
        """

        language = language or settings.LANGUAGE_CODE
        value = super().get(language, default)
        return value if value is not None else default 
Example #5
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 #6
Source File: field.py    From django-localized-fields with MIT License 6 votes vote down vote up
def validate(self, value: LocalizedValue, *_):
        """Validates that the values has been filled in for all required
        languages.

        Exceptions are raises in order to notify the user
        of invalid values.

        Arguments:
            value:
                The value to validate.
        """

        if self.null:
            return

        for lang in self.required:
            lang_val = getattr(value, settings.LANGUAGE_CODE)

            if lang_val is None:
                raise IntegrityError(
                    'null value in column "%s.%s" violates '
                    "not-null constraint" % (self.name, lang)
                ) 
Example #7
Source File: test_settings.py    From janeway with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_save_translated_setting_without_default_lang(self):
        setting_name = "test_save_translated_setting_without_default_lang"
        setting_value = "plátano"
        expected_result = ""
        setting = setting_handler.create_setting(
                "test_group", setting_name,
                type="text",
                pretty_name="Pretty Name",
                description=None,
                is_translatable=True,
        )
        setting_handler.save_setting(
                "test_group", setting_name,
                journal=self.journal_one,
                value=setting_value,
        )
        with helpers.activate_translation(settings.LANGUAGE_CODE):
            result = setting_handler.get_setting(
                    "test_group", setting_name,
                    journal=self.journal_one,
            )
        self.assertEqual(result.value, expected_result) 
Example #8
Source File: setting_handler.py    From janeway with GNU Affero General Public License v3.0 6 votes vote down vote up
def _get_plugin_setting(plugin, setting, journal, lang, create, fallback):
    try:
        setting = models.PluginSettingValue.objects.language(lang).get(
            setting__plugin=plugin,
            setting=setting,
            journal=journal
        )
        return setting
    except models.PluginSettingValue.DoesNotExist:
        if lang == settings.LANGUAGE_CODE:
            if create:
                return save_plugin_setting(plugin, setting.name, '', journal)
            else:
                raise IndexError('Plugin setting does not exist and will not be created.')
        else:
            # Switch get the setting and start a translation
            setting = models.PluginSettingValue.objects.language(settings.LANGUAGE_CODE).get(
                setting__plugin=plugin,
                setting=setting,
                journal=journal
            )

            if not fallback:
                setting.translate(lang)
            return setting 
Example #9
Source File: trans_real.py    From bioforum with MIT License 6 votes vote down vote up
def gettext(message):
    """
    Translate the 'message' string. It uses the current thread to find the
    translation object to use. If no current translation is activated, the
    message will be run through the default translation object.
    """
    global _default

    eol_message = message.replace('\r\n', '\n').replace('\r', '\n')

    if len(eol_message) == 0:
        # Return an empty value of the corresponding type if an empty message
        # is given, instead of metadata, which is the default gettext behavior.
        result = type(message)("")
    else:
        _default = _default or translation(settings.LANGUAGE_CODE)
        translation_object = getattr(_active, "value", _default)

        result = translation_object.gettext(eol_message)

    if isinstance(message, SafeData):
        return mark_safe(result)

    return result 
Example #10
Source File: setting_handler.py    From janeway with GNU Affero General Public License v3.0 6 votes vote down vote up
def save_plugin_setting(plugin, setting_name, value, journal):
    setting = models.PluginSetting.objects.get(name=setting_name)
    lang = get_language() or settings.LANGUAGE_CODE
    lang = lang if setting.is_translatable else settings.LANGUAGE_CODE

    setting_value, created = models.PluginSettingValue.objects.language(lang).get_or_create(
        setting__plugin=plugin,
        setting=setting,
        journal=journal
    )

    if setting.types == 'json':
        value = json.dumps(value)

    if setting.types == 'boolean':
        value = 'on' if value else ''

    setting_value.value = value

    setting_value.save()

    return setting_value 
Example #11
Source File: process_crossref_events.py    From janeway with GNU Affero General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        """Collects Crossref Events, parses them and stores new events locally.

        :param args: None
        :param options: None
        :return: None
        """

        translation.activate(settings.LANGUAGE_CODE)

        file_name = '{date}.json'.format(date=timezone.localdate())
        file_path = os.path.join(settings.BASE_DIR, 'files', 'temp', file_name)

        if os.path.isfile(file_path):

            # Process file
            print('Existing file found.')
            process_events()

        else:

            # Fetch data
            print('Fetching data from crossref event tracking API.')
            fetch_crossref_data()
            process_events() 
Example #12
Source File: utils.py    From pasportaservo with GNU Affero General Public License v3.0 6 votes vote down vote up
def geocode(query, country='', private=False, annotations=False, multiple=False):
    key = SiteConfiguration.get_solo().opencage_api_key
    lang = settings.LANGUAGE_CODE
    if not query:
        return
    params = {'language': lang}
    if not annotations:
        params.update({'no_annotations': int(not annotations)})
    if private:
        params.update({'no_record': int(private)})
    if country:
        params.update({'countrycode': country})
    result = geocoder.opencage(query, key=key, params=params, maxRows=15 if multiple else 1)
    logging.getLogger('PasportaServo.geo').debug(
        "Query: %s\n\tResult: %s\n\tConfidence: %d", query, result, result.confidence)
    result.point = Point(result.xy, srid=SRID) if result.xy else None
    return result 
Example #13
Source File: problem.py    From online-judge with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_contest_queryset(self):
        queryset = self.profile.current_contest.contest.contest_problems.select_related('problem__group') \
            .defer('problem__description').order_by('problem__code') \
            .annotate(user_count=Count('submission__participation', distinct=True)) \
            .order_by('order')
        queryset = TranslatedProblemForeignKeyQuerySet.add_problem_i18n_name(queryset, 'i18n_name',
                                                                             self.request.LANGUAGE_CODE,
                                                                             'problem__name')
        return [{
            'id': p['problem_id'],
            'code': p['problem__code'],
            'name': p['problem__name'],
            'i18n_name': p['i18n_name'],
            'group': {'full_name': p['problem__group__full_name']},
            'points': p['points'],
            'partial': p['partial'],
            'user_count': p['user_count'],
        } for p in queryset.values('problem_id', 'problem__code', 'problem__name', 'i18n_name',
                                   'problem__group__full_name', 'points', 'partial', 'user_count')] 
Example #14
Source File: test_slug_fields.py    From django-localized-fields with MIT License 5 votes vote down vote up
def test_unique_slug_update(cls):
        obj = cls.Model.objects.create(
            title={settings.LANGUAGE_CODE: "mytitle"}
        )
        assert obj.slug.get() == "mytitle"
        obj.title.set(settings.LANGUAGE_CODE, "othertitle")
        obj.save()
        assert obj.slug.get() == "othertitle" 
Example #15
Source File: field.py    From django-localized-fields with MIT License 5 votes vote down vote up
def __init__(
        self, *args, required: Union[bool, List[str]] = None, **kwargs
    ):
        """Initializes a new instance of :see:LocalizedField."""

        super(LocalizedField, self).__init__(*args, required=required, **kwargs)

        if (self.required is None and self.blank) or self.required is False:
            self.required = []
        elif self.required is None and not self.blank:
            self.required = [settings.LANGUAGE_CODE]
        elif self.required is True:
            self.required = [lang_code for lang_code, _ in settings.LANGUAGES] 
Example #16
Source File: descriptor.py    From django-localized-fields with MIT License 5 votes vote down vote up
def __set__(self, instance, value):
        if isinstance(value, str):
            language = translation.get_language() or settings.LANGUAGE_CODE
            self.__get__(instance).set(
                language, value
            )  # pylint: disable=no-member
        else:
            instance.__dict__[self.field.name] = value 
Example #17
Source File: setting_handler.py    From janeway with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_requestless_setting(setting_group, setting, journal):
    lang = settings.LANGUAGE_CODE
    setting = core_models.Setting.objects.get(name=setting)
    setting = core_models.SettingValue.objects.language(lang).get(
        setting__group__name=setting_group,
        setting=setting,
        journal=journal
    )

    return setting 
Example #18
Source File: value.py    From django-localized-fields with MIT License 5 votes vote down vote up
def translate(self, language: Optional[str] = None) -> Optional[str]:
        """Gets the value in the specified language (or active language).

        Arguments:
            language:
                The language to get the value in. If not specified,
                the currently active language is used.

        Returns:
            The value in the specified (or active) language. If no value
            is available in the specified language, the value is returned
            in one of the fallback languages.
        """

        target_language = (
            language or translation.get_language() or settings.LANGUAGE_CODE
        )

        fallback_config = getattr(settings, "LOCALIZED_FIELDS_FALLBACKS", {})

        target_languages = fallback_config.get(
            target_language, [settings.LANGUAGE_CODE]
        )
        target_languages.insert(0, target_language)

        for lang_code in target_languages:
            value = self.get(lang_code)
            if value:
                return value or None

        return None 
Example #19
Source File: setting_handler.py    From janeway with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_setting(
        setting_group, setting_name,
        journal=None,
        create=False,
        fallback=True,
        default=True,
):
    """ Returns a matching SettingValue for the language in context

    It no journal is passed it returns the default setting directly. If
    fallback or default are True, it will attempt to returnthe base language
    and/or the default value respectively (in that order)
    :setting_group: (str) The group__name of the Setting
    :setting_name: (str) The name of the Setting
    :journal: (Journal object) The journal for which this setting is relevant.
        If None, returns the default value
    :create: If True, a journal override will be created if one is not present
    :fallback: If True, it will attempt to return the value for the base
        language when no value is available for the current language
    :default: If True, returns the default SettingValue when no journal specific
        value is present
    """
    setting = core_models.Setting.objects.get(name=setting_name)
    lang = get_language() if setting.is_translatable else settings.LANGUAGE_CODE
    try:
        return _get_setting(
            setting_group, setting, journal, lang, create, fallback, default)
    except Exception as e:
        logger.critical(
                "Failed to load setting for context:\n"
                "setting_name: {0},\n"
                "journal: {1},\n"
                "fallback: {2},\n"
                "request language: {3},\n"
                "settings language: {4},\n"
                "".format(
                    setting_name, journal, fallback,
                    lang, settings.LANGUAGE_CODE
                )
            )
        raise e 
Example #20
Source File: test_integer_field.py    From django-localized-fields with MIT License 5 votes vote down vote up
def test_get_default_value(self):
        """Tests whether getting the value in a specific language properly
        returns the specified default in case it is not available."""

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

        secondary_language = settings.LANGUAGES[-1][0]
        assert obj.score.get(secondary_language) is None
        assert obj.score.get(secondary_language, 1337) == 1337 
Example #21
Source File: test_integer_field.py    From django-localized-fields with MIT License 5 votes vote down vote up
def test_none_if_illegal_value_stored(self):
        """Tests whether None is returned for a language if the value stored in
        the database is not an integer."""

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

        with connection.cursor() as cursor:
            table_name = self.TestModel._meta.db_table
            cursor.execute("update %s set score = 'en=>haha'" % table_name)

        obj.refresh_from_db()
        assert obj.score.get(settings.LANGUAGE_CODE) is None 
Example #22
Source File: forms.py    From janeway with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(ConfiguratorForm, self).__init__(*args, **kwargs)
        self.fields['default_section'].queryset = models.Section.objects.language().fallbacks(
            settings.LANGUAGE_CODE,
        ).filter(
            journal=self.instance.journal,
        )
        self.fields[
            'default_license'].queryset = models.Licence.objects.filter(
            journal=self.instance.journal,
        ) 
Example #23
Source File: render_pdf.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def add_arguments(self, parser):
        parser.add_argument('code', help='code of problem to render')
        parser.add_argument('directory', nargs='?', help='directory to store temporaries')
        parser.add_argument('-l', '--language', default=settings.LANGUAGE_CODE,
                            help='language to render PDF in')
        parser.add_argument('-p', '--phantomjs', action='store_const', const=PhantomJSPdfMaker,
                            default=DefaultPdfMaker, dest='engine')
        parser.add_argument('-s', '--slimerjs', action='store_const', const=SlimerJSPdfMaker, dest='engine')
        parser.add_argument('-c', '--chrome', '--puppeteer', action='store_const',
                            const=PuppeteerPDFRender, dest='engine')
        parser.add_argument('-S', '--selenium', action='store_const', const=SeleniumPDFRender, dest='engine') 
Example #24
Source File: problem.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_title(self):
        return _('Submit to %s') % self.object.translated_name(self.request.LANGUAGE_CODE) 
Example #25
Source File: problem.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_content_title(self):
        return mark_safe(
            escape(_('Submit to %s')) % format_html(
                '<a href="{0}">{1}</a>',
                reverse('problem_detail', args=[self.object.code]),
                self.object.translated_name(self.request.LANGUAGE_CODE),
            ),
        ) 
Example #26
Source File: problem.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_paginator(self, queryset, per_page, orphans=0,
                      allow_empty_first_page=True, **kwargs):
        paginator = DiggPaginator(queryset, per_page, body=6, padding=2, orphans=orphans,
                                  allow_empty_first_page=allow_empty_first_page, **kwargs)
        if not self.in_contest:
            # Get the number of pages and then add in this magic.
            # noinspection PyStatementEffect
            paginator.num_pages

            queryset = queryset.add_i18n_name(self.request.LANGUAGE_CODE)
            sort_key = self.order.lstrip('-')
            if sort_key in self.sql_sort:
                queryset = queryset.order_by(self.order, 'id')
            elif sort_key == 'name':
                queryset = queryset.order_by(self.order.replace('name', 'i18n_name'), 'id')
            elif sort_key == 'group':
                queryset = queryset.order_by(self.order + '__name', 'id')
            elif sort_key == 'solved':
                if self.request.user.is_authenticated:
                    profile = self.request.profile
                    solved = user_completed_ids(profile)
                    attempted = user_attempted_ids(profile)

                    def _solved_sort_order(problem):
                        if problem.id in solved:
                            return 1
                        if problem.id in attempted:
                            return 0
                        return -1

                    queryset = list(queryset)
                    queryset.sort(key=_solved_sort_order, reverse=self.order.startswith('-'))
            elif sort_key == 'type':
                if self.show_types:
                    queryset = list(queryset)
                    queryset.sort(key=lambda problem: problem.types_list[0] if problem.types_list else '',
                                  reverse=self.order.startswith('-'))
            paginator.object_list = queryset
        return paginator 
Example #27
Source File: problem.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        with translation.override(settings.LANGUAGE_CODE):
            return self.render_to_response(self.get_context_data(
                object=self.object,
            )) 
Example #28
Source File: mails.py    From byro with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        if "locales" not in kwargs:
            from byro.common.models import Configuration

            config = Configuration.get_solo()
            kwargs["locales"] = [config.language or settings.LANGUAGE_CODE]
        return super().__init__(*args, **kwargs) 
Example #29
Source File: test_integer_field.py    From django-localized-fields with MIT License 5 votes vote down vote up
def test_order_by(self):
        """Tests whether ordering by a :see:LocalizedIntegerField key works
        expected."""

        # using key transforms (score__en) in order_by(..) is only
        # supported since Django 2.1
        # https://github.com/django/django/commit/2162f0983de0dfe2178531638ce7ea56f54dd4e7#diff-0edd853580d56db07e4020728d59e193

        if django.VERSION < (2, 1):
            return

        model = get_fake_model(
            {
                "score": LocalizedIntegerField(
                    default={settings.LANGUAGE_CODE: 1337}, null=True
                )
            }
        )

        model.objects.create(score=dict(en=982))
        model.objects.create(score=dict(en=382))
        model.objects.create(score=dict(en=1331))

        res = list(
            model.objects.values_list("score__en", flat=True).order_by(
                "-score__en"
            )
        )
        assert res == [1331, 982, 382] 
Example #30
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