django.conf.settings.LANGUAGES

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

200 Examples 7

Example 1

Project: talk.org
Source File: context_processors.py
View license
def i18n(request):
    context_extras = {}
    context_extras['LANGUAGES'] = settings.LANGUAGES
    if hasattr(request, 'LANGUAGE_CODE'):
        context_extras['LANGUAGE_CODE'] = request.LANGUAGE_CODE
    else:
        context_extras['LANGUAGE_CODE'] = settings.LANGUAGE_CODE

    from django.utils import translation
    context_extras['LANGUAGE_BIDI'] = translation.get_language_bidi()

    return context_extras

Example 2

Project: django-cms-search
Source File: fields.py
View license
    def prepare_template(self, obj):
        content = []
        current_lang = get_language()
        try:
            for lang, lang_name in settings.LANGUAGES:
                activate(lang)
                content.append(self._prepare_template(obj, needs_request=self.needs_request))
        finally:
            activate(current_lang)
        return '\n'.join(content)

Example 3

Project: django-cms-search
Source File: indexes.py
View license
    def __new__(cls, name, bases, attrs):
        if 'HaystackTrans' in attrs:
            for field in getattr(attrs['HaystackTrans'], 'fields', []):
                if field not in attrs:
                    continue
                for lang_tuple in settings.LANGUAGES:
                    lang = lang_tuple[0]
                    safe_lang = lang.replace('-', '_')
                    attrs['%s_%s' % (field, safe_lang)] = cls._get_field_copy(attrs[field], lang)
                    if 'prepare_' + field in attrs:
                        attrs['prepare_%s_%s' % (field, safe_lang)] = MultiLangPrepareDecorator(lang)(attrs['prepare_' + field])
        return super(MultiLanguageIndexBase, cls).__new__(cls, name, bases, attrs)

Example 4

View license
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 5

Project: GAE-Bulk-Mailer
Source File: trans_real.py
View license
def get_language_from_path(path, supported=None):
    """
    Returns the language-code if there is a valid language-code
    found in the `path`.
    """
    if supported is None:
        from django.conf import settings
        supported = dict(settings.LANGUAGES)
    regex_match = language_code_prefix_re.match(path)
    if regex_match:
        lang_code = regex_match.group(1)
        if lang_code in supported and check_for_language(lang_code):
            return lang_code

Example 6

View license
def i18n():
    from django.utils import translation

    return {
        'LANGUAGES': settings.LANGUAGES,
        'LANGUAGE_CODE': translation.get_language(),
        'LANGUAGE_BIDI': translation.get_language_bidi(),
    }

Example 7

Project: pretix
Source File: i18n.py
View license
    def __init__(self, *args, **kwargs):
        fields = []
        defaults = {
            'widget': self.widget,
            'max_length': kwargs.pop('max_length', None),
        }
        self.langcodes = kwargs.pop('langcodes', [l[0] for l in settings.LANGUAGES])
        self.one_required = kwargs.get('required', True)
        kwargs['required'] = False
        kwargs['widget'] = kwargs['widget'](
            langcodes=self.langcodes, field=self, **kwargs.pop('widget_kwargs', {})
        )
        defaults.update(**kwargs)
        for lngcode in self.langcodes:
            defaults['label'] = '%s (%s)' % (defaults.get('label'), lngcode)
            fields.append(forms.CharField(**defaults))
        super().__init__(
            fields=fields, require_all_fields=False, *args, **kwargs
        )

Example 8

Project: pretix
Source File: middleware.py
View license
def get_language_from_request(request: HttpRequest) -> str:
    """
    Analyzes the request to find what language the user wants the system to
    show. Only languages listed in settings.LANGUAGES are taken into account.
    If the user requests a sublanguage where we have a main language, we send
    out the main language.
    """
    global _supported
    if _supported is None:
        _supported = OrderedDict(settings.LANGUAGES)

    return (
        get_language_from_user_settings(request)
        or get_language_from_session_or_cookie(request)
        or get_language_from_event(request)
        or get_language_from_browser(request)
        or get_default_language()
    )

Example 9

Project: pycon
Source File: forms.py
View license
def get_language_choices():
    # In settings, we had to mark the language names for translation using
    # a dummy ugettext to avoid circular imports, so now we need to actually
    # retrieve their translations
    return [(value, _(name))
            for value, name
            in settings.LANGUAGES]

Example 10

Project: cmsplugin-rt
Source File: plugins.py
View license
    def setUp(self):
        self.super_user = User(username="test", is_staff = True, is_active = True, is_superuser = True)
        self.super_user.set_password("test")
        self.super_user.save()

        self.slave = User(username="slave", is_staff=True, is_active=True, is_superuser=False)
        self.slave.set_password("slave")
        self.slave.save()


        self.FIRST_LANG = settings.LANGUAGES[0][0]
        self.SECOND_LANG = settings.LANGUAGES[1][0]
        
        self._login_context = self.login_user_context(self.super_user)
        self._login_context.__enter__()

Example 11

Project: django-shop
Source File: 0002_add_i18n.py
View license
def add_translation(apps, schema_editor):
    Commodity = apps.get_model('myshop', 'Commodity')
    Translation = apps.get_model('myshop', 'CommodityTranslation')
    for sc in Commodity.objects.all():
        for lang in settings.LANGUAGES:
            trans = Translation.objects.create(language_code=lang[0], caption=sc.caption,
                                               slug=sc.slug, product_name=sc.product_name,
                                               master=sc)
            trans.save()

Example 12

Project: django-shop
Source File: indexes.py
View license
    def index_queryset(self, using=None):
        """Used when the entire index for model is updated."""
        if using in dict(settings.LANGUAGES):
            self.language = using
        else:
            self.language = settings.LANGUAGE_CODE
        return self.get_model().objects.indexable()

Example 13

View license
def translate(path, code, get_params):

    # Strip existing code (if any) from path
    codes = [lang[0] for lang in settings.LANGUAGES]
    pattern = '|'.join(codes)
    pattern = '^/(%s)' % pattern
    path = re.sub(pattern, '', path)

    # Prepend a language code for all but default language
    defcode = settings.LANGUAGE_CODE
    if code == defcode and settings.PREFIX_DEFAULT_LOCALE is False:
        return u'%s%s' % (path, get_params)
    else:
        return '/%s%s%s' % (code, path, get_params)

Example 14

Project: django-mothertongue
Source File: tests.py
View license
    def test_url_es(self):
      
        # Create mock request for spanish
        request = self.rf.get('/es/')
        context = RequestContext(request)
        self.assertEqual(context['LANGUAGE_CODE'], 'es')
        self.assertEqual(context['mothertongue_path_lang_prefix'], '/es/')
        self.assertEqual(context['request'].META['PATH_INFO'], '/es/')
        self.assertNotEqual(context['mothertongue_language_nav'], '')
        self.assertEqual(context['LANGUAGES'], settings.LANGUAGES)

Example 15

Project: pari
Source File: article_views.py
View license
    def get_context_data(self, **kwargs):
        context = super(ArticleDetail, self).get_context_data(**kwargs)
        article = context['blog_post']
        translations = []
        for language in settings.LANGUAGES[1:]:
            content = getattr(article, "content_{0}".format(language[0]), None)
            if content and content.strip():
                translations.append(language)
        language = self.request.GET.get("hl")
        if language and language in [ii[0] for ii in settings.LANGUAGES]:
            translation.activate(language)
            self.request.session[LANGUAGE_SESSION_KEY] = language
        context['translations'] = translations
        context['related_articles'] = article.related_posts.filter(status=CONTENT_STATUS_PUBLISHED)[:5]
        if article.featured_video or article.featured_audio:
            obj = context['object']
            obj.oembed_data = json.loads(obj.oembed_data)
            context['object'] = obj
        return context

Example 16

View license
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 17

View license
@lru_cache.lru_cache()
def get_languages():
    """
    Cache of settings.LANGUAGES in an OrderedDict for easy lookups by key.
    """
    return OrderedDict(settings.LANGUAGES)

Example 18

View license
    def test_fixture_and_elasticsearch_up(self):
        documents = Document.objects.all()
        self.assertEqual(len(documents), self.count)
        languages = [l[0] for l in settings.LANGUAGES]
        es = ElasticsearchMultilingualSearchBackend('default', **Data.connection_options)
        self.assertEqual(languages, es.languages)

        self.assertTrue(es.conn.ping())
        info = es.conn.info()
        self.assertEqual('elasticsearch', info['cluster_name'])
        self.assertEqual(200, info['status'])

Example 19

View license
    @mock.patch('elasticsearch.Elasticsearch')
    def test_mocking_works(self, mock_obj):
        # create a backend instance
        es = ElasticsearchMultilingualSearchBackend('default', **Data.connection_options)
        for language in settings.LANGUAGES:
            self.assertIn(language[0], es.existing_mapping.keys())
        # in the constructor, an Elasticsearche instance is created as 'conn' property.
        self.assertTrue(isinstance(es.conn, mock.Mock))
        self.assertIsNot(es.conn, mock_obj)  # a new mock is created.
        self.assertFalse(es.silently_fail)
        indices = mock_indices()  # use the indices mock from the mocks module.
        es.conn.attach_mock(indices, 'indices')
        self.assertEqual(es.conn.indices.get_mapping(), Data.existing_mapping)
        es.setup()
        # Data.connection_options.INDEX_NAME
        indices.get_mapping.assert_any_call(index='testproject-en')
        indices.get_mapping.assert_any_call(index='testproject-de')
        indices.get_mapping.assert_any_call(index='testproject-ru')

Example 20

Project: django-slim
Source File: helpers.py
View license
def get_default_language():
    """
    Gets default language.

    :return str:
    """
    return settings.LANGUAGES[0][0]

Example 21

Project: django-slim
Source File: helpers.py
View license
def get_languages():
    """
    Gets available languages.

    :return iterable:
    """
    if not USE_LOCAL_LANGUAGE_NAMES:
        return settings.LANGUAGES
    else:
        languages = []
        for lang_code, lang_name in settings.LANGUAGES:
            try:
                lang_name = get_language_info(lang_code)['name_local']
            except Exception as e:
                pass
            languages.append((lang_code, lang_name))
        return languages

Example 22

Project: shuup
Source File: variable_variation_forms.py
View license
    def get_editor_args(self):
        return {
            "languages": [
                {
                    "code": code,
                    "name": get_language_name(code)
                } for code in to_language_codes(settings.LANGUAGES)
                ],
            "variables": self.get_variable_data()
        }

Example 23

Project: shuup
Source File: edit.py
View license
    def get_form_defs(self):
        if not self.object.get_available_attribute_queryset():
            return
        yield TemplatedFormDef(
            "attributes",
            ProductAttributesForm,
            template_name="shuup/admin/products/_edit_attribute_form.jinja",
            required=False,
            kwargs={"product": self.object, "languages": settings.LANGUAGES}
        )

Example 24

Project: django-easymode
Source File: languagecode.py
View license
def get_language_codes():
    """
    Retrieves all the language codes defined in ``settings.LANGUAGES``.
    
    >>> settings.LANGUAGES = (('en','English'),('de','German'),('nl-be','Belgium dutch'),('fr-be','Belgium french'),)
    >>> sorted( get_language_codes() )
    ['de', 'en', 'fr-be', 'nl-be']
    
    :rtype: A :class:`list` of language codes.
    """
    return dict(settings.LANGUAGES).keys()

Example 25

View license
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 26

Project: splunk-webframework
Source File: trans_real.py
View license
def get_language_from_path(path, supported=None):
    """
    Returns the language-code if there is a valid language-code
    found in the `path`.
    """
    if supported is None:
        from django.conf import settings
        supported = dict(settings.LANGUAGES)
    regex_match = language_code_prefix_re.match(path)
    if regex_match:
        lang_code = regex_match.group(1)
        if lang_code in supported and check_for_language(lang_code):
            return lang_code

Example 27

Project: tendenci
Source File: utils.py
View license
def get_languages_with_local_name():
    """
    Get a list of tuples of available languages with local name.
    """
    return [(ll['code'], '%s (%s)' % (ll['name_local'], ll['code'])) for ll in
            [translation.get_language_info(l[0])
             for l in settings.LANGUAGES]]

Example 28

Project: tendenci
Source File: models.py
View license
    @property
    def lang(self):
        if not self.language in [l[0] for l in settings.LANGUAGES]:
            self.language = 'en'
            self.save()
        return self.language

Example 29

Project: transifex
Source File: utils.py
View license
def invalidate_template_cache(fragment_name, *variables):
    """
    This function invalidates a template cache named `fragment_name` and with
    variables which are included in *variables. For example:

    {% cache 500 project_details project.slug %}
        ...
    {% endcache %}

    We invalidate this by calling:
     -  invalidate_template_cache("project_details", project.slug)
    """
    for lang,code in settings.LANGUAGES:
        cur_vars = list(variables)
        cur_vars.append(unicode(lang))
        args = md5_constructor(u':'.join([urlquote(var) for var in cur_vars]))
        cache_key = 'template.cache.%s.%s' % (fragment_name, args.hexdigest())
        cache.delete(cache_key)

Example 30

Project: transifex
Source File: cache.py
View license
def invalidate_template_cache(fragment_name, *variables):
    """This function invalidates a template cache.

    The template cache is named `fragment_name` and the variables are
    included in *variables. For example:

    {% cache 500 project_details project.slug LANGUAGE_CODE%}
        ...
    {% endcache %}

    We invalidate this by calling:
     -  invalidate_template_cache("project_details", project.slug)
    """
    for lang,code in settings.LANGUAGES:
        cur_vars = list(variables)
        cur_vars.append(unicode(lang))
        args = md5_constructor(u':'.join([urlquote(var) for var in cur_vars]))
        cache_key = 'template.cache.%s.%s' % (fragment_name, args.hexdigest())
        cache.delete(cache_key)

Example 31

Project: transifex
Source File: cache.py
View license
def set_fragment_content(node, key_vars, context):
    """Set the rendered content of a template fragment."""
    try:
        for code, lang in settings.LANGUAGES:
            cur_vars = list(key_vars)
            cur_vars.append(unicode(code))
            args = md5_constructor(u':'.join([urlquote(var) for var in cur_vars]))
            cache_key = 'template.cache.%s.%s' % (node.fragment_name, args.hexdigest())
            context['use_l10n'] = True
            context['LANGUAGE_CODE'] = code
            value = node.nodelist.render(context=Context(context))
            cache.set(cache_key, value, settings.CACHE_MIDDLEWARE_SECONDS)
    except Exception, e:
        invalidate_template_cache(node.fragment_name, key_vars.keys())

Example 32

Project: python-useful
Source File: i18n.py
View license
def get_safe_langcode():
    """
    Returns two-letter code of the active language.
    Is always one of the supported languages. 'en' is expected to exist!
    """
    lang = get_language()[:2].lower()
    return lang if lang in dict(settings.LANGUAGES) else 'en'

Example 33

Project: django-datatrans
Source File: middleware.py
View license
def get_language_from_request(request):
    from django.conf import settings
    supported = dict(settings.LANGUAGES)

    if hasattr(request, 'session'):
        lang_code = request.session.get('django_language', None)
        if lang_code in supported and lang_code is not None:
            return lang_code
    return settings.LANGUAGE_CODE

Example 34

Project: django-datatrans
Source File: utils.py
View license
def get_current_language():
    """
    Get the current language
    """
    lang = translation.get_language()
    if lang is None:
        return get_default_language()
    current = [l[0] for l in settings.LANGUAGES if l[0] == lang]
    if len(current) == 0:
        lang = lang.split('-')[0]
        current = [l[0] for l in settings.LANGUAGES if l[0] == lang]
    if len(current) == 0:
        # Fallback to default language code
        return get_default_language()
    
    return current[0]

Example 35

Project: django-ninecms
Source File: admin.py
View license
    def formfield_for_choice_field(self, db_field, request=None, **kwargs):
        """ Override choices of languages field to respect settings
        :param db_field: the database field name
        :param request: the request object
        :param kwargs: keyword arguments such as the queryset
        :return: parent method return
        """
        if db_field.name == 'language':
            kwargs['choices'] = (('', '---------'),) + settings.LANGUAGES
        return super(MenuItemAdmin, self).formfield_for_choice_field(db_field, request, **kwargs)

Example 36

Project: django-ninecms
Source File: setup.py
View license
def url_with_lang(url):
    """ Get a url with language, if more than 1 language is defined (and less than 86 which are django default)
    :param url: the url to be returned
    :return: the url with language, if applicable
    """
    prefix = ''
    if 1 < len(settings.LANGUAGES) < 80:  # pragma: nocover
        prefix = '/' + settings.LANGUAGE_CODE
    return prefix + url

Example 37

Project: django-linguo
Source File: models.py
View license
    def __init__(self, *args, **kwargs):
        self._force_language = None

        # Rewrite any keyword arguments for translatable fields
        language = get_current_language()
        for field in self._meta.translatable_fields:
            if field in kwargs.keys():
                attrname = get_real_field_name(field, language)
                if attrname != field:
                    kwargs[attrname] = kwargs[field]
                    del kwargs[field]

        # We have to force the primary language before initializing or else
        # our "proxy" property will prevent the primary language values from being returned.
        self._force_language = get_normalized_language(settings.LANGUAGES[0][0])
        super(MultilingualModel, self).__init__(*args, **kwargs)
        self._force_language = None

Example 38

View license
    def get_missing_languages(self, field_name, db_table):
        """
        Gets only missings fields.
        """
        db_table_fields = self.get_table_fields(db_table)
        for lang_code, lang_name in settings.LANGUAGES:
            if build_localized_fieldname(field_name, lang_code) not in db_table_fields:
                yield lang_code

Example 39

Project: django-i18nurls
Source File: middleware.py
View license
    def get_language_from_path(self, path):
        regex_match = language_code_prefix_re.match(path)
        if regex_match:
            language_code = regex_match.group(1)
            if language_code in dict(settings.LANGUAGES):
                return language_code
        return None

Example 40

Project: plan
Source File: middleware.py
View license
    def __init__(self):
        self.languages = {}  # Localised semester type -> lang
        self.values = {}     # Localised semester type -> db value

        for lang, name in settings.LANGUAGES:
            with translation.override(lang):
                for value, slug in Semester.SEMESTER_SLUG:
                    self.languages[unicode(slug)] = lang
                    self.values[unicode(slug)] = value

Example 41

Project: plan
Source File: middleware.py
View license
    def guess_language_from_accept_header(self, request):
        supported = dict(settings.LANGUAGES)
        accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')

        for lang, unused in trans_internals.parse_accept_lang_header(accept):
            if lang == '*':
                break
            lang = lang.split('-')[0].lower()
            if settings.LANGUAGE_FALLBACK.get(lang, lang) in supported:
                return lang
        return settings.LANGUAGE_CODE

Example 42

Project: cgstudiomap
Source File: context_processors.py
View license
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 43

Project: django-nonrel
Source File: views.py
View license
    def setUp(self):
        self.old_LANGUAGES = settings.LANGUAGES
        self.old_LANGUAGE_CODE = settings.LANGUAGE_CODE
        settings.LANGUAGES = (('en', 'English'),)
        settings.LANGUAGE_CODE = 'en'
        self.old_TEMPLATE_DIRS = settings.TEMPLATE_DIRS
        settings.TEMPLATE_DIRS = (
            os.path.join(os.path.dirname(__file__), 'templates'),
        )

Example 44

Project: django-nonrel
Source File: context_processors.py
View license
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 45

Project: avos
Source File: tests.py
View license
    def test_display_language(self):
        # Add an unknown language to LANGUAGES list
        settings.LANGUAGES += (('unknown', 'Unknown Language'),)

        res = self.client.get(INDEX_URL)
        # Known language
        self.assertContains(res, 'English')
        # Unknown language
        self.assertContains(res, 'Unknown Language')

Example 46

Project: hue
Source File: locale.py
View license
    def __init__(self):
        self._supported_languages = SortedDict(settings.LANGUAGES)
        self._is_language_prefix_patterns_used = False
        for url_pattern in get_resolver(None).url_patterns:
            if isinstance(url_pattern, LocaleRegexURLResolver):
                self._is_language_prefix_patterns_used = True
                break

Example 47

Project: hue
Source File: trans_real.py
View license
def get_language_from_path(path, supported=None, strict=False):
    """
    Returns the language-code if there is a valid language-code
    found in the `path`.

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

Example 48

Project: django-translation-manager
Source File: admin.py
View license
    def compile_translations_view(self, request):
        manager = Manager()
        for language, language_name in settings.LANGUAGES:
            manager.update_po_from_db(lang=language)
        post_save.send(sender=None, request=request)

        self.message_user(request, _("admin-translation_manager-translations_compiled"))
        return HttpResponseRedirect(reverse("admin:translation_manager_translationentry_changelist"))

Example 49

View license
    def load_data_from_po(self):
        import os

        for lang, lang_name in settings.LANGUAGES:
            for path in settings.LOCALE_PATHS:
                locale = get_dirname_from_lang(lang)
                po_pattern = os.path.join(path, locale, "LC_MESSAGES", "*.po")
                for pofile in glob(po_pattern):
                    if settings.DEBUG:
                        print ("processing pofile", pofile)
                    self.store_to_db(pofile=pofile, locale=locale, store_translations=True)

        self.postprocess()

Example 50

Project: django-simple-seo
Source File: simple_seo.py
View license
    @staticmethod
    def _check_field_i18n(field):
        """
        Avoid fields that has _XX lang prefix
        """
        if not getattr(settings, 'USE_I18N', None) or field is None:
            return False
        for lang in settings.LANGUAGES:
            if '_'+lang[0] in field.name:
                return True

        return False