我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.conf.settings.LANGUAGES。
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])
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])
def generate_operations(): operations = [] for code, name in settings.LANGUAGES: operations += [ migrations.AddField( model_name='warehouse', name='address_%s' % code, field=models.CharField(db_index=True, max_length=255, null=True, verbose_name='Address'), ), migrations.AddField( model_name='warehouse', name='title_%s' % code, field=models.CharField(db_index=True, max_length=255, null=True, verbose_name='Title'), ), ] return operations
def kolibri_language_globals(context): lang_dir = "rtl" if get_language_bidi() else "ltr" js = """ <script> var languageCode = '{lang_code}'; var languageDir = '{lang_dir}'; var languages = JSON.parse('{languages}'); </script> """.format( lang_code=get_language(), lang_dir=lang_dir, languages=json.dumps({code: { # Format to match the schema of the content Language model 'id': code, 'lang_name': name, 'lang_direction': get_language_info(code)['bidi'] } for code, name in settings.LANGUAGES}), ) return mark_safe(js)
def set_default_language(lang): """ Set the default language for this installation of Kolibri. Any running instance of Kolibri needs to be restarted in order for this change to work. """ from kolibri.utils import conf from django.conf import settings valid_languages = [l[0] for l in settings.LANGUAGES] if lang in valid_languages: conf.config['LANGUAGE_CODE'] = lang conf.save() else: msg = "Invalid language code {langcode}. Must be one of: {validlangs}".format( langcode=lang, validlangs=valid_languages ) logging.warning(msg)
def get(self, request, *args, **kwargs): url = request.GET.get('next', request.META.get('HTTP_REFERER', '/')) url = url if is_safe_url(url, host=request.get_host()) else '/' resp = HttpResponseRedirect(url) locale = request.GET.get('locale') if locale in [lc for lc, ll in settings.LANGUAGES]: if request.user.is_authenticated: request.user.locale = locale request.user.save() max_age = 10 * 365 * 24 * 60 * 60 resp.set_cookie(settings.LANGUAGE_COOKIE_NAME, locale, max_age=max_age, expires=(datetime.utcnow() + timedelta(seconds=max_age)).strftime( '%a, %d-%b-%Y %H:%M:%S GMT'), domain=settings.SESSION_COOKIE_DOMAIN) with override(locale): messages.success(request, phrases.cfp.locale_change_success) return resp
def _select_locale(self, request): supported = request.event.locales if (hasattr(request, 'event') and request.event) else settings.LANGUAGES language = ( self._language_from_user(request, supported) or self._language_from_cookie(request, supported) or self._language_from_browser(request, supported) ) if hasattr(request, 'event') and request.event: language = language or request.event.locale translation.activate(language) request.LANGUAGE_CODE = translation.get_language() with suppress(pytz.UnknownTimeZoneError): if request.user.is_authenticated: tzname = request.user.timezone elif hasattr(request, 'event') and request.event: tzname = request.event.timezone else: tzname = settings.TIME_ZONE timezone.activate(pytz.timezone(tzname)) request.timezone = tzname
def handle(self, **options): """ Find all translation files and populate the database with them. """ for lang_code, lang_name in settings.LANGUAGES: filepaths = find_pofiles(lang_code, third_party_apps=options['include_third_party']) if len(filepaths) > 0: print("{} filepaths found for language {}".format(len(filepaths), lang_name)) for fp in filepaths: obj, created = TranslationFile.objects.get_or_create( name=app_name_from_filepath(fp), filepath=fp, language_code=lang_code ) self.stdout.write("{} Created: {}".format(fp, created))
def fix_tree(cls, destructive=False): """ Fixes the plugin tree by first calling treebeard fix_tree and the recalculating the correct position property for each plugin. """ from cms.utils.plugins import reorder_plugins super(CMSPlugin, cls).fix_tree(destructive) for placeholder in Placeholder.objects.all(): for language, __ in settings.LANGUAGES: order = CMSPlugin.objects.filter( placeholder_id=placeholder.pk, language=language, parent_id__isnull=True ).order_by('position').values_list('pk', flat=True) reorder_plugins(placeholder, None, language, order) for plugin in CMSPlugin.objects.filter( placeholder_id=placeholder.pk, language=language).order_by('depth', 'path'): order = CMSPlugin.objects.filter( parent_id=plugin.pk ).order_by('position').values_list('pk', flat=True) reorder_plugins(placeholder, plugin.pk, language, order)
def get_new_page_data(self, parent_id=''): page_data = { 'title': 'test page %d' % self.counter, 'slug': 'test-page-%d' % self.counter, 'language': settings.LANGUAGES[0][0], 'template': 'nav_playground.html', 'parent': parent_id, 'site': 1, 'pagepermission_set-TOTAL_FORMS': 0, 'pagepermission_set-INITIAL_FORMS': 0, 'pagepermission_set-MAX_NUM_FORMS': 0, 'pagepermission_set-2-TOTAL_FORMS': 0, 'pagepermission_set-2-INITIAL_FORMS': 0, 'pagepermission_set-2-MAX_NUM_FORMS': 0 } # required only if user haves can_change_permission self.counter += 1 return page_data
def test_create_page_api(self): page_data = { 'title': 'root', 'slug': 'root', 'language': settings.LANGUAGES[0][0], 'template': 'nav_playground.html', } page = create_page(**page_data) page = page.reload() page.publish('en') self.assertEqual(Page.objects.count(), 2) self.assertTrue(page.is_home) self.assertTrue(page.publisher_public.is_home) self.assertEqual(list(Title.objects.drafts().values_list('path', flat=True)), [u'']) self.assertEqual(list(Title.objects.public().values_list('path', flat=True)), [u''])
def test_create_page_api_with_long_username(self): page_data = { 'title': 'root', 'slug': 'root', 'language': settings.LANGUAGES[0][0], 'template': 'nav_playground.html', 'created_by': self._create_user( 'V' * constants.PAGE_USERNAME_MAX_LENGTH + 'ERY-LONG-USERNAME', is_staff=True, is_superuser=True, ), } page = create_page(**page_data) self.assertEqual(Page.objects.count(), 1) self.assertLessEqual(len(page.created_by), constants.PAGE_USERNAME_MAX_LENGTH) self.assertRegexpMatches(page.created_by, r'V+\.{3} \(id=\d+\)') self.assertLessEqual(len(page.changed_by), constants.PAGE_USERNAME_MAX_LENGTH) self.assertRegexpMatches(page.changed_by, r'V+\.{3} \(id=\d+\)') self.assertEqual(list(Title.objects.drafts().values_list('path', flat=True)), [u''])
def test_delete_page_no_template(self): page_data = { 'title': 'root', 'slug': 'root', 'language': settings.LANGUAGES[0][0], 'template': 'nav_playground.html', } page = create_page(**page_data) page.template = 'no_such_template.html' signals.pre_save.disconnect(pre_save_page, sender=Page, dispatch_uid='cms_pre_save_page') signals.post_save.disconnect(post_save_page, sender=Page, dispatch_uid='cms_post_save_page') page.save(no_signals=True) signals.pre_save.connect(pre_save_page, sender=Page, dispatch_uid='cms_pre_save_page') signals.post_save.connect(post_save_page, sender=Page, dispatch_uid='cms_post_save_page') page.delete() self.assertEqual(Page.objects.count(), 0)
def test_edit_page_other_site_and_language(self): """ Test that a page can edited via the admin when your current site is different from the site you are editing and the language isn't available for the current site. """ self.assertEqual(Site.objects.all().count(), 1) site = Site.objects.create(domain='otherlang', name='otherlang', pk=2) # Change site for this session page_data = self.get_new_page_data() page_data['site'] = site.pk page_data['title'] = 'changed title' self.assertEqual(site.pk, 2) TESTLANG = get_cms_setting('LANGUAGES')[site.pk][0]['code'] page_data['language'] = TESTLANG superuser = self.get_superuser() with self.login_user_context(superuser): response = self.client.post(URL_CMS_PAGE_ADD, page_data) self.assertRedirects(response, URL_CMS_PAGE) page = Page.objects.get(title_set__slug=page_data['slug'], publisher_is_draft=True) with LanguageOverride(TESTLANG): self.assertEqual(page.get_title(), 'changed title')
def test_plugin_parent_classes_from_settings(self): page = api.create_page("page", "nav_playground.html", "en", published=True) placeholder = page.placeholders.get(slot='body') ParentClassesPlugin = type('ParentClassesPlugin', (CMSPluginBase,), dict(parent_classes=['TextPlugin'], render_plugin=False)) plugin_pool.register_plugin(ParentClassesPlugin) plugin = api.add_plugin(placeholder, ParentClassesPlugin, settings.LANGUAGES[0][0]) plugin = plugin.get_plugin_class_instance() ## assert baseline self.assertEqual(['TextPlugin'], plugin.get_parent_classes(placeholder.slot, page)) CMS_PLACEHOLDER_CONF = { 'body': { 'parent_classes': { 'ParentClassesPlugin': ['TestPlugin'], } } } with self.settings(CMS_PLACEHOLDER_CONF=CMS_PLACEHOLDER_CONF): self.assertEqual(['TestPlugin'], plugin.get_parent_classes(placeholder.slot, page)) plugin_pool.unregister_plugin(ParentClassesPlugin)
def setUp(self): self.super_user = self._create_user("test", True, True) self.slave = self._create_user("slave", True) self._login_context = self.login_user_context(self.super_user) self._login_context.__enter__() # create 3 sections self.sections = [] self.section_pks = [] for i in range(3): section = Section.objects.create(name="section %s" % i) self.sections.append(section) self.section_pks.append(section.pk) self.section_count = len(self.sections) # create 10 articles by section for section in self.sections: for j in range(10): Article.objects.create( title="article %s" % j, section=section ) self.FIRST_LANG = settings.LANGUAGES[0][0] self.SECOND_LANG = settings.LANGUAGES[1][0]
def test_placeholder_tag(self): request = self.get_request('/', language=settings.LANGUAGES[0][0]) template = "{% load cms_tags %}{% render_placeholder placeholder %}" output = self.render_template_obj(template, {}, request) self.assertEqual(output, "") placeholder = Placeholder.objects.create(slot="test") output = self.render_template_obj(template, {'placeholder': placeholder}, request) self.assertEqual(output, "") self.assertEqual(placeholder.cmsplugin_set.count(), 0) add_plugin(placeholder, "TextPlugin", settings.LANGUAGES[0][0], body="test") self.assertEqual(placeholder.cmsplugin_set.count(), 1) placeholder = self.reload(placeholder) output = self.render_template_obj(template, {'placeholder': placeholder}, request) self.assertEqual(output, "test")
def get_default_language(language_code=None, site_id=None): """ Returns default language depending on settings.LANGUAGE_CODE merged with best match from get_cms_setting('LANGUAGES') Returns: language_code """ if not language_code: language_code = get_language_code(settings.LANGUAGE_CODE) languages = get_language_list(site_id) # first try if there is an exact language if language_code in languages: return language_code # otherwise split the language code if possible, so iso3 language_code = language_code.split("-")[0] if not language_code in languages: return settings.LANGUAGE_CODE return language_code
def get_languages(): if settings.SITE_ID != hash(settings.SITE_ID): raise ImproperlyConfigured( "SITE_ID must be an integer" ) if not settings.USE_I18N: return _ensure_languages_settings( {settings.SITE_ID: [{'code': settings.LANGUAGE_CODE, 'name': settings.LANGUAGE_CODE}]}) if settings.LANGUAGE_CODE not in dict(settings.LANGUAGES): raise ImproperlyConfigured( 'LANGUAGE_CODE "%s" must have a matching entry in LANGUAGES' % settings.LANGUAGE_CODE ) languages = getattr(settings, 'CMS_LANGUAGES', { settings.SITE_ID: [{'code': code, 'name': _(name)} for code, name in settings.LANGUAGES] }) if VERIFIED in languages: return languages return _ensure_languages_settings(languages)
def __init__(self, *args, **kwargs): fields = [] defaults = { 'widget': self.widget, 'max_length': kwargs.pop('max_length', None), } self.locales = kwargs.pop('locales', [l[0] for l in settings.LANGUAGES]) self.one_required = kwargs.get('required', True) require_all_fields = kwargs.pop('require_all_fields', False) kwargs['required'] = False kwargs['widget'] = kwargs['widget']( locales=self.locales, field=self, **kwargs.pop('widget_kwargs', {}) ) defaults.update(**kwargs) for lngcode in self.locales: defaults['label'] = '%s (%s)' % (defaults.get('label'), lngcode) field = forms.CharField(**defaults) field.locale = lngcode fields.append(field) super().__init__( fields=fields, require_all_fields=False, *args, **kwargs ) self.require_all_fields = require_all_fields
def modeltranslation_fields(self): """ Helper function for generating modeltranslation multi language fields. Args: self: (south.v2.SchemaMigration): Migrations instance. Returns: tuple: tuple with modeltranslation fields. """ if modeltranslation(): title = tuple([("title_{language}".format(**{"language": language, }), self.gf("django.db.models.fields.CharField")(db_index=True, max_length=255, null=True, blank=True)) for language in list(dict(settings.LANGUAGES).keys())]) text = tuple([("text_{language}".format(**{"language": language, }), self.gf("django.db.models.fields.TextField")(null=True, blank=True)) for language in list(dict(settings.LANGUAGES).keys())]) return title + text else: return tuple()
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
def __init__(self, *args, required: Union[bool, List[str]]=False, **kwargs): """Initializes a new instance of :see:LocalizedFieldForm.""" fields = [] for lang_code, _ in settings.LANGUAGES: field_options = dict( required=required if type(required) is bool else (lang_code in required), label=lang_code ) fields.append(self.field_class(**field_options)) super(LocalizedFieldForm, self).__init__( fields, required=required if type(required) is bool else True, require_all_fields=False, *args, **kwargs ) # set 'required' attribute for each widget separately for field, widget in zip(self.fields, self.widget.widgets): widget.is_required = field.required
def compress(self, value: List[str]) -> value_class: """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
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 ]
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
def get_language_codes() -> List[str]: """Gets a list of all available language codes. This looks at your project's settings.LANGUAGES and returns a flat list of the configured language codes. Arguments: A flat list of all availble language codes in your project. """ return [ lang_code for lang_code, _ in settings.LANGUAGES ]
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(['', ''], ['', ''])
def test_init(): """Tests whether the :see:__init__ function correctly handles parameters""" field = LocalizedField(blank=True) assert field.required == [] field = LocalizedField(blank=False) assert field.required == [settings.LANGUAGE_CODE] field = LocalizedField(required=True) assert field.required == [lang_code for lang_code, _ in settings.LANGUAGES] field = LocalizedField(required=False) assert field.required == []
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
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()
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()
def __init__(self, *args, **kwargs): super(UpdateEmailingForm, self).__init__(*args, **kwargs) subscription_choices = [(subs_type.id, subs_type.name) for subs_type in SubscriptionType.objects.all()] self.fields["subscription_type"].widget = forms.Select(choices=subscription_choices) newsletter_choices = [(newsletter.id, newsletter.subject) for newsletter in Newsletter.objects.all()] self.fields["newsletter"].widget = forms.Select(choices=newsletter_choices, attrs={'class': 'form-control'}) if not getattr(settings, 'BALAFON_EMAILING_SENDER_CHOICES', None): self.fields["from_email"].widget = forms.HiddenInput() else: self.fields["from_email"].widget = forms.Select(choices=settings.BALAFON_EMAILING_SENDER_CHOICES) if not getattr(settings, 'LANGUAGES', None) or len(settings.LANGUAGES) < 2: self.fields["lang"].widget = forms.HiddenInput() else: language_choices = crm_settings.get_language_choices(_(u"Favorite language of the contact")) self.fields["lang"].widget = forms.Select(choices=language_choices, attrs={'class': 'form-control'})
def test_article_link_force_language(self): if len(settings.LANGUAGES) > 1: lang = settings.LANGUAGES[0][0] tpl = Template( '''{% spaceless %}{% load balafon_profile_perm %} {% if_can_do_article "test" %}HELLO{% else %}SORRY{% endif %}{% endspaceless %}''' ) request = self._request() request.LANGUAGE_CODE = settings.LANGUAGES[1][0] html = tpl.render(Context({'request': request})) self.assertEqual(html, "HELLO") article_class = get_article_class() self.assertEqual(article_class.objects.count(), 1) a = article_class.objects.all()[0] self.assertEqual(a.slug, "test")
def lang(self): for lang_code, lang_name in settings.LANGUAGES: if lang_code == self.request.LANGUAGE_CODE: return self.request.LANGUAGE_CODE.lower() return settings.LANGUAGES[0][0].lower() # ###########################################
def __unicode__(self): name_res = _("Missing brand name") for lang_code, lang_name in settings.LANGUAGES: translation = getattr(self, lang_code.lower(), None) if translation is not None: if translation.name and len(translation.name) > 0: name_res = u"{}".format(smart_text(translation.name)) else: name_res = u"{}".format(smart_text(translation.slug)) return name_res
def process_request(self, request): """ Modify request. :param request: django request instance. :type request: django.http.request.HttpRequest. """ l_path = request.path.split("/") request.session["no_lang_path"] = request.path if l_path[1] in list(dict(settings.LANGUAGES).keys()): del l_path[1] no_lang_path = "/".join(l_path) request.session["no_lang_path"] = no_lang_path
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')
def test_index(self): """ Test the index view. """ response = self.client.get('/') self.assertEqual(response.status_code, 200) # def test_index_locales(self): # """ # Test index in all locales specified in settings. # """ # for language in settings.LANGUAGES: # locale = language[0] # # response = self.client.get('/{}'.format(locale)) # self.assertEqual(response.status_code, 301) # # response = self.client.get('/{}/'.format(locale)) # self.assertEqual(response.status_code, 200) # def test_non_existant_locale(self): # """ # Tests a non-existant locale. Currently 404 response. # """ # response = self.client.get('/fr') # self.assertEqual(response.status_code, 404) # # response = self.client.get('/fr/') # self.assertEqual(response.status_code, 404)
def get_urls(self, page=1, site=None, protocol=None): # Determine protocol if self.protocol is not None: protocol = self.protocol if protocol is None: protocol = 'http' # Determine domain if site is None: if django_apps.is_installed('django.contrib.sites'): Site = django_apps.get_model('sites.Site') try: site = Site.objects.get_current() except Site.DoesNotExist: pass if site is None: raise ImproperlyConfigured( "To use sitemaps, either enable the sites framework or pass " "a Site/RequestSite object in your view." ) domain = site.domain if getattr(self, 'i18n', False): urls = [] current_lang_code = translation.get_language() for lang_code, lang_name in settings.LANGUAGES: translation.activate(lang_code) urls += self._urls(page, protocol, domain) translation.activate(current_lang_code) else: urls = self._urls(page, protocol, domain) return urls
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
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()
def get_languages(): """ Cache of settings.LANGUAGES in an OrderedDict for easy lookups by key. """ return OrderedDict(settings.LANGUAGES)