Python django.conf.settings.LANGUAGE_CODE Examples

The following are 30 code examples for showing how to use django.conf.settings.LANGUAGE_CODE(). 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: django-classified   Author: slyapustin   File: classified.py    License: 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
Project: bioforum   Author: reBiocoder   File: trans_real.py    License: 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 3
Project: pasportaservo   Author: tejoesperanto   File: utils.py    License: 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 4
Project: online-judge   Author: DMOJ   File: problem.py    License: 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 5
Project: janeway   Author: BirkbeckCTP   File: process_crossref_events.py    License: 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 6
Project: janeway   Author: BirkbeckCTP   File: setting_handler.py    License: 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 7
Project: janeway   Author: BirkbeckCTP   File: setting_handler.py    License: 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 8
Project: janeway   Author: BirkbeckCTP   File: test_settings.py    License: 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 9
Project: django-localized-fields   Author: SectorLabs   File: value.py    License: 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 10
Project: django-localized-fields   Author: SectorLabs   File: field.py    License: 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 11
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 12
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 13
Project: django-localized-fields   Author: SectorLabs   File: test_integer_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": 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 14
Project: jbox   Author: jpush   File: django_wsgi.py    License: MIT License 5 votes vote down vote up
def make_wsgi_application():
    # validate models
    s = StringIO()
    if get_validation_errors(s):
        s.seek(0)
        error = s.read()
        msg = "One or more models did not validate:\n%s" % error
        print(msg, file=sys.stderr)
        sys.stderr.flush()
        sys.exit(1)

    translation.activate(settings.LANGUAGE_CODE)
    if django14:
        return get_internal_wsgi_application()
    return WSGIHandler() 
Example 15
Project: GTDWeb   Author: lanbing510   File: cache.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _i18n_cache_key_suffix(request, cache_key):
    """If necessary, adds the current locale or time zone to the cache key."""
    if settings.USE_I18N or settings.USE_L10N:
        # first check if LocaleMiddleware or another middleware added
        # LANGUAGE_CODE to request, then fall back to the active language
        # which in turn can also fall back to settings.LANGUAGE_CODE
        cache_key += '.%s' % getattr(request, 'LANGUAGE_CODE', get_language())
    if settings.USE_TZ:
        # The datetime module doesn't restrict the output of tzname().
        # Windows is known to use non-standard, locale-dependent names.
        # User-defined tzinfo classes may return absolutely anything.
        # Hence this paranoid conversion to create a valid cache key.
        tz_name = force_text(get_current_timezone_name(), errors='ignore')
        cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
    return cache_key 
Example 16
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 17
Project: GTDWeb   Author: lanbing510   File: trans_real.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _init_translation_catalog(self):
        """Creates a base catalog using global django translations."""
        settingsfile = upath(sys.modules[settings.__module__].__file__)
        localedir = os.path.join(os.path.dirname(settingsfile), 'locale')
        use_null_fallback = True
        if self.__language == settings.LANGUAGE_CODE:
            # default lang should be present and parseable, if not
            # gettext will raise an IOError (refs #18192).
            use_null_fallback = False
        translation = self._new_gnu_trans(localedir, use_null_fallback)
        self.plural = translation.plural
        self._info = translation._info.copy()
        self._catalog = translation._catalog.copy() 
Example 18
Project: GTDWeb   Author: lanbing510   File: trans_real.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _add_fallback(self):
        """Sets the GNUTranslations() fallback with the default language."""
        # Don't set a fallback for the default language or any English variant
        # (as it's empty, so it'll ALWAYS fall back to the default language)
        if self.__language == settings.LANGUAGE_CODE or self.__language.startswith('en'):
            return
        default_translation = translation(settings.LANGUAGE_CODE)
        self.add_fallback(default_translation) 
Example 19
Project: GTDWeb   Author: lanbing510   File: trans_real.py    License: GNU General Public License v2.0 5 votes vote down vote up
def catalog():
    """
    Returns the current active catalog for further processing.
    This can be used if you need to modify the catalog or want to access the
    whole message catalog instead of just translating one string.
    """
    global _default

    t = getattr(_active, "value", None)
    if t is not None:
        return t
    if _default is None:
        _default = translation(settings.LANGUAGE_CODE)
    return _default 
Example 20
Project: GTDWeb   Author: lanbing510   File: trans_real.py    License: GNU General Public License v2.0 5 votes vote down vote up
def do_ntranslate(singular, plural, number, translation_function):
    global _default

    t = getattr(_active, "value", None)
    if t is not None:
        return getattr(t, translation_function)(singular, plural, number)
    if _default is None:
        _default = translation(settings.LANGUAGE_CODE)
    return getattr(_default, translation_function)(singular, plural, number) 
Example 21
Project: GTDWeb   Author: lanbing510   File: runfcgi.py    License: GNU General Public License v2.0 5 votes vote down vote up
def handle(self, *args, **options):
        warnings.warn(
            "FastCGI support has been deprecated and will be removed in Django 1.9.",
            RemovedInDjango19Warning)

        from django.conf import settings
        from django.utils import translation
        # Activate the current language, because it won't get activated later.
        try:
            translation.activate(settings.LANGUAGE_CODE)
        except AttributeError:
            pass
        from django.core.servers.fastcgi import runfastcgi
        runfastcgi(args) 
Example 22
Project: anytask   Author: znick   File: models.py    License: MIT License 5 votes vote down vote up
def get_lang_text(text, lang):
    text_ = check_json(text)
    if text_:
        lang = lang if lang in text_ else settings.LANGUAGE_CODE
        return text_[lang]
    return unicode(text) 
Example 23
Project: anytask   Author: znick   File: models.py    License: MIT License 5 votes vote down vote up
def get_title(self, lang=settings.LANGUAGE_CODE):
        return escape(get_lang_text(self.title, lang)) 
Example 24
Project: anytask   Author: znick   File: models.py    License: MIT License 5 votes vote down vote up
def get_description(self, lang=settings.LANGUAGE_CODE):
        return get_lang_text(self.task_text, lang) 
Example 25
Project: anytask   Author: znick   File: models.py    License: MIT License 5 votes vote down vote up
def get_field_repr(self, field, lang=settings.LANGUAGE_CODE):
        name = field.name

        if name == 'student_name':
            return get_user_link(self.student)
        if name == 'responsible_name':
            if self.responsible:
                return get_user_link(self.responsible)
            return None
        if name == 'followers_names':
            followers = map(
                lambda x: u'<a class="user" href="{0}">{1}</a>'.format(
                    x.get_absolute_url(), get_user_fullname(x)
                ),
                self.followers.all()
            )
            return ', '.join(followers)
        if name == 'course_name':
            course = self.task.course
            return u'<a href="{0}">{1}</a>'.format(course.get_absolute_url(), course.name)
        if name == 'task_name':
            task = self.task
            return task.get_title(lang)
        if name == 'comment':
            return None
        if name == 'status':
            return self.status_field.get_name(lang)
        if name == 'mark':
            return self.score()
        if name == 'review_id' and self.task.rb_integrated:
            return u'<a href="{1}/r/{0}">{0}</a>'.format(
                self.get_byname('review_id'),
                settings.RB_API_URL,
            )
        if name == 'run_id' and self.task.contest_integrated:
            return u'<a href="https://contest.yandex.ru/contest/{1}/run-report/{0}">{0}</a>'.format(
                self.get_byname('run_id'),
                self.task.contest_id,
            )

        return self.get_field_value(field) 
Example 26
Project: anytask   Author: znick   File: issueFilter.py    License: MIT License 5 votes vote down vote up
def qs(self):
        issues = super(IssueFilter, self).qs
        issues_count = len(issues)
        lang = self.data_full.get('lang', settings.LANGUAGE_CODE)
        timezone = self.data_full.get('timezone', settings.TIME_ZONE)
        start = int(self.data_full.get('start', 0))
        end = start + int(self.data_full.get('length', 50))
        data = []
        issues = issues[start:end]
        for issue in issues:
            student = issue.student
            responsible = issue.responsible
            data.append({
                "start": start,
                "has_issue_access": issue.task.has_issue_access(),
                "issue_url": issue.get_absolute_url(),
                "student_url": student.get_absolute_url(),
                "student_name": u'%s %s' % (student.last_name, student.first_name),
                "task_title": issue.task.get_title(lang),
                "update_time": issue.update_time.astimezone(timezone_pytz(timezone)).strftime('%d-%m-%Y %H:%M'),
                "mark": float(issue.score()),
                "status_name": issue.status_field.get_name(lang),
                "status_color": issue.status_field.color,
                "responsible_url": responsible.get_absolute_url() if responsible else "",
                "responsible_name": u'%s %s' % (responsible.last_name, responsible.first_name) if responsible else "",
                "DT_RowId": "row_issue_" + str(issue.id),
                "DT_RowData": {
                    "id": issue.id
                },
            })

        self.response = {
            'draw': self.data_full.get('draw', None),
            'recordsTotal': issues_count,
            'recordsFiltered': issues_count,
            'data': data,
            'url': "queue?" + self.data_full.get('filter', ''),
        }

        return Issue.objects.none() 
Example 27
Project: bioforum   Author: reBiocoder   File: locale.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
        i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf)
        language = translation.get_language_from_request(request, check_path=i18n_patterns_used)
        language_from_path = translation.get_language_from_path(request.path_info)
        if not language_from_path and i18n_patterns_used and not prefixed_default_language:
            language = settings.LANGUAGE_CODE
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language() 
Example 28
Project: bioforum   Author: reBiocoder   File: cache.py    License: MIT License 5 votes vote down vote up
def _i18n_cache_key_suffix(request, cache_key):
    """If necessary, add the current locale or time zone to the cache key."""
    if settings.USE_I18N or settings.USE_L10N:
        # first check if LocaleMiddleware or another middleware added
        # LANGUAGE_CODE to request, then fall back to the active language
        # which in turn can also fall back to settings.LANGUAGE_CODE
        cache_key += '.%s' % getattr(request, 'LANGUAGE_CODE', get_language())
    if settings.USE_TZ:
        # The datetime module doesn't restrict the output of tzname().
        # Windows is known to use non-standard, locale-dependent names.
        # User-defined tzinfo classes may return absolutely anything.
        # Hence this paranoid conversion to create a valid cache key.
        tz_name = force_text(get_current_timezone_name(), errors='ignore')
        cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
    return cache_key 
Example 29
Project: bioforum   Author: reBiocoder   File: trans_null.py    License: MIT License 5 votes vote down vote up
def get_language_bidi():
    return settings.LANGUAGE_CODE in settings.LANGUAGES_BIDI 
Example 30
Project: bioforum   Author: reBiocoder   File: trans_real.py    License: MIT License 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()