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.
144 Examples
3
Example 51
def get_paths(self):
paths = []
for lang_code, lang_name in settings.LANGUAGES:
# posts
activate(lang_code)
items = Post.objects.filter(
is_published=True, language=lang_code).order_by('-pubdate')
paths.extend([i.get_absolute_url() for i in items])
paths.append(i18n_reverse(lang_code, 'blog_archive'))
paths.append(i18n_reverse(lang_code, 'blog_feed'))
return paths
3
Example 52
def get_context_data(self, **kwargs):
data = super(MailFormView, self).get_context_data(**kwargs)
data['mail_name'] = self.mail_name
preview_messages = {}
for lang_code, lang_name in settings.LANGUAGES:
message = self.get_mail_preview(self.mail_name, lang_code)
preview_messages[lang_code] = message
data['preview_messages'] = preview_messages
return data
3
Example 53
def __init__(self, *args, **kwargs):
super(LanguageSelectField, self).__init__(
label=_("Language"),
choices=settings.LANGUAGES,
widget=Select2Widget,
*args, **kwargs)
3
Example 54
def get_language_tabs(self, request, available_languages):
tabs = []
get = request.GET.copy()
language = self._language(request)
for key, name in settings.LANGUAGES:
get['language'] = key
url = '%s?%s' % (request.path, get.urlencode())
if language == key:
status = 'current'
elif key in available_languages:
status = 'available'
else:
status = 'empty'
tabs.append((url, name, key, status))
return tabs
3
Example 55
def is_primary_language(language=None):
"""
Returns true if current or passed language is the primary language for this
site. (The primary language is defined as the first language in
settings.LANGUAGES.)
"""
if not language:
language = translation.get_language()
return language == settings.LANGUAGES[0][0]
3
Example 56
Project: django-klingon Source File: test_api.py
@override_settings(KLINGON_DEFAULT_LANGUAGE='en')
def test_create_translations_with_default_language(self):
self.book.translate()
self.assertEquals(
len(Translation.objects.all()),
(len(settings.LANGUAGES) - 1) * len(self.book.translatable_fields)
)
# nothing should happen if you run translate tiwce
self.book.translate()
self.assertEquals(
len(Translation.objects.all()),
(len(settings.LANGUAGES) - 1) * len(self.book.translatable_fields),
)
3
Example 57
Project: badges.mozilla.org Source File: context_processors.py
def i18n(request):
return {'LANGUAGES': settings.LANGUAGES,
'LANG': settings.LANGUAGE_URL_MAP.get(translation.get_language())
or translation.get_language(),
'DIR': 'rtl' if translation.get_language_bidi() else 'ltr',
}
3
Example 58
Project: django-fluent-contents Source File: models.py
def get_cache_keys(self):
# When the shared content is saved, make sure all rendering output PTRs are cleared.
# The 'slug' could have changed. Whether the Placeholder output is cleared,
# depends on whether those objects are altered too.
if self.is_cross_site or self._was_cross_site:
sites = list(Site.objects.all().values_list('pk', flat=True))
else:
sites = [self.parent_site_id]
keys = []
for site_id in sites:
for language_code, _ in settings.LANGUAGES:
keys.append(get_shared_content_cache_key_ptr(site_id, self._old_slug, language_code))
return keys
3
Example 59
def items(self):
pages = [
AS(reverse('faq_page', kwargs={'locale': ''})), #FAQ
# Add more static pages
]
for lang, _ in settings.LANGUAGES:
pages.append(AS('/%s/' % lang, "weekly", 1))
return pages
3
Example 60
Project: django-parler Source File: admin.py
def all_languages_column(self, object):
"""
The language column which can be included in the ``list_display``.
It also shows untranslated languages
"""
all_languages = [code for code, __ in settings.LANGUAGES]
return self._languages_column(object, all_languages, span_classes='all-languages')
3
Example 61
def get_project(self, request, **kwargs):
self.language_code = request.GET.get('lang', 'en')
if self.language_code not in dict(settings.LANGUAGES):
self.language_code = "en"
translation.activate(self.language_code)
limit = int(request.GET.get('limit', 50))
if limit > 50:
limit = 50
bundles = []
found_projects = SearchQuerySet().models(I4pProject).filter_and(text__icontains=request.GET['q'], language_codes__icontains=self.language_code, sites=settings.SITE_ID)[:limit]
for project in found_projects:
if project.object:
bundles.append(self.build_bundle(obj=project, data={"language_code": self.language_code, "slug": project.object.slug, "title": project.object.title}, request=request))
to_be_serialized = [self.full_dehydrate(bundle, for_list=True) for bundle in bundles]
to_be_serialized = self.alter_list_data_to_serialize(request, to_be_serialized)
return self.create_response(request, to_be_serialized)
3
Example 62
def flush_includes(self, languages=True):
if not languages:
return
if languages is True:
languages = [lc for (lc, _ln) in settings.LANGUAGES]
flush_ssi_includes([
template % (self.pk, lang)
for template in [
'/katalog/p/%d/short.%s.html',
'/katalog/p/%d/mini.%s.html',
]
for lang in languages
])
3
Example 63
Project: wagtail-modeltranslation Source File: patch_wagtailadmin.py
def _patch_elasticsearch_fields(model):
for field in model.search_fields:
# Check if the field is a SearchField and if it is one of the fields registered for translation
if field.__class__ is SearchField and field.field_name in WagtailTranslator._translation_options.fields:
# If it is we create a clone of the original SearchField to keep all the defined options
# and replace its name by the translated one
for lang in settings.LANGUAGES:
translated_field = copy.deepcopy(field)
translated_field.field_name = build_localized_fieldname(field.field_name, lang[0])
model.search_fields = model.search_fields + (translated_field,)
3
Example 64
Project: django-klingon Source File: test_api.py
def test_create_translations(self):
self.book.translate()
self.assertEquals(
Translation.objects.count(),
len(settings.LANGUAGES * len(self.book.translatable_fields)),
)
# nothing should happen if you run translate tiwce
self.book.translate()
self.assertEquals(
len(Translation.objects.all()),
len(settings.LANGUAGES * len(self.book.translatable_fields)),
)
3
Example 65
def get_paths(self):
paths = []
for lang_code, lang_name in settings.LANGUAGES:
activate(lang_code)
items = list(
I18NTag.objects.filter(language=lang_code).order_by('name'))
paths.extend([i.get_absolute_url() for i in items])
for tag in items:
paths.append(i18n_reverse(lang_code, 'blog_tag_feed',
kwargs={'slug': tag.slug_no_locale}))
paths.append(i18n_reverse(lang_code, 'blog_tags'))
return paths
3
Example 66
def test_home_page_returns_correct_html(self):
"""
Tests that the HomeView seems to use the correct template
"""
sample_component = self.create_sample_component(type_id="gimp.desktop")
self.create_sample_featured_app(component=sample_component)
response = self.client.get(reverse('home'))
template_html = render_to_string(
'home.html',
{"LANGUAGES": settings.LANGUAGES[:]}
)
self.assertAlmostEqual(
len(response.content.decode()),
len(template_html),
delta=150
)
3
Example 67
def __init__(self, *args, **kwargs):
kwargs.setdefault('max_length', 5)
kwargs.setdefault('choices', settings.LANGUAGES)
kwargs.setdefault('default', settings.LANGUAGE_CODE)
super(LanguageField, self).__init__(*args, **kwargs)
3
Example 68
Project: kuma Source File: test_templates.py
def test_page_renders_locales(self):
"""Load the page and verify it contains all the locales for l10n."""
response = self.client.get(reverse('wiki.select_locale',
args=[self.d.slug]),
follow=True)
eq_(200, response.status_code)
doc = pq(response.content)
eq_(len(settings.LANGUAGES) - 1, # All except for 1 (en-US)
len(doc('#select-locale ul.locales li')))
3
Example 69
def add_fields(self, form, index):
super(BaseTranslationFormSet, self).add_fields(form, index)
# Add the language code automagically
if not 'language_code' in form.fields:
form.fields['language_code'] = CharField(
required=True, initial=form.instance.language_code,
widget=Select(choices=(('', '--'),)+settings.LANGUAGES)
)
# Add language_code to self._meta.fields so it is included in validation stage
try:
form._meta.fields.append('language_code')
except AttributeError: #pragma: no cover
form._meta.fields += ('language_code',)
# Remove the master foreignkey, we have this from self.instance already
if 'master' in form.fields:
del form.fields['master']
3
Example 70
Project: django-tcms Source File: admin.py
def __init__(self, req, admin):
model = admin.model
field = model._meta.get_field('path')
super(LocaleFilterSpec, self).__init__(field, req, {}, model, admin)
self.lookup_kwarg = '%s__locale' % field.name
self.lookup_val = req.GET.get(self.lookup_kwarg, None)
self.lookup_choices = settings.LANGUAGES
self.title = lambda: 'locale'
3
Example 71
def validate(self, value):
value_too_short = True
if isinstance(value, basestring):
if len(value.strip()) >= self.min_length:
value_too_short = False
else:
for locale, string in value.items():
if locale.lower() not in settings.LANGUAGES:
raise ValidationError(
self.error_messages['unknown_locale'].format(
lang_code=repr(locale)))
if string and (len(string.strip()) >= self.min_length):
value_too_short = False
break
if self.min_length and value_too_short:
raise ValidationError(
self.error_messages['min_length'].format(num=self.min_length))
3
Example 72
def setUp(self):
super(EventTestCaseSetupMixin, self).setUp()
# since aldryn_events namespace is created inside of a migration 0016
# use something different for test purposes
self.app_config = EventsConfig.objects.create(
namespace='events_test_namespace'
)
self.template = get_cms_setting('TEMPLATES')[0][0]
self.language = settings.LANGUAGES[0][0]
3
Example 73
def what(self, page, args, default=None):
language = args.get('language',False)
if not language:
language = settings.LANGUAGES[0][0]
elif language not in (x[0] for x in settings.LANGUAGES):
language = template.Variable(language).resolve(self.render_context)
return _translate_page_into(page, language, default=default)
3
Example 74
Project: feincms Source File: translations.py
def admin_translationinline(model, inline_class=admin.StackedInline, **kwargs):
"""
Returns a new inline type suitable for the Django administration::
from django.contrib import admin
from myapp.models import News, NewsTranslation
admin.site.register(News,
inlines=[
admin_translationinline(NewsTranslation),
],
)
"""
kwargs['extra'] = 1
kwargs['max_num'] = len(settings.LANGUAGES)
kwargs['model'] = model
return type(
str(model.__class__.__name__ + 'Inline'), (inline_class,), kwargs)
3
Example 75
def get_fieldsets(self, request, obj=None):
fieldsets = copy.deepcopy(self._fieldsets)
# remove language field if only one language is available
if len(settings.LANGUAGES) <= 1:
fieldsets[0][1]['fields'] = fieldsets[0][1]['fields'][:-1]
# remove placeholder field if CMS 3.0
if LooseVersion(cms.__version__) >= LooseVersion('3.0'):
del fieldsets[-1]
return fieldsets
3
Example 76
def get_language_from_path(path):
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)
except LookupError:
return None
3
Example 77
Project: django-widgy Source File: models.py
@property
def default_children(self):
return [
(l[0], self.child_class, (), {'language_code': l[0]})
for l in settings.LANGUAGES
]
3
Example 78
Project: fjord Source File: context_processors.py
def i18n(request):
return {
'LANGUAGES': settings.LANGUAGES,
'LANG': (settings.LANGUAGE_URL_MAP.get(translation.get_language())
or translation.get_language()),
'DIR': 'rtl' if translation.get_language_bidi() else 'ltr',
}
3
Example 79
def test_language_list(self):
response = self.client.get('/api/languages/')
self.assertIsNotNone(response.data)
self.assertEquals(len(response.data), len(settings.LANGUAGES))
for lang in settings.LANGUAGES:
find_lang = lambda x: x['code'] == lang[0]
response_lang = filter(find_lang, response.data)[0]
self.assertIsNotNone(response_lang)
self.assertTrue(response_lang['name'] == lang[1])
3
Example 80
def setUp(self):
self.template = get_cms_setting('TEMPLATES')[0][0]
self.language = settings.LANGUAGES[0][0]
self.page = api.create_page(
'page', self.template, self.language, published=True,
apphook='BlogApp', apphook_namespace='Blog'
)
api.create_title('fr', 'french page', self.page)
self.page.publish('fr')
self.placeholder = self.page.placeholders.all()[0]
self.user = User.objects.create(first_name='Peter', last_name='Muster')
3
Example 81
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'
)
,)
0
Example 82
Project: oioioi Source File: tests.py
def test_language_flags(self):
response = self.client.get('/', follow=True)
for lang_code, _lang_name in settings.LANGUAGES:
self.assertIn(lang_code + '.png', response.content)
0
Example 83
Project: cmsplugin-rt Source File: plugins.py
def test_remove_plugin_not_associated_to_page(self):
"""
Test case for PlaceholderField
"""
page_data = self.get_new_page_data()
response = self.client.post(URL_CMS_PAGE_ADD, page_data)
page = Page.objects.all()[0]
# add a plugin
plugin_data = {
'plugin_type':"TextPlugin",
'language':settings.LANGUAGES[0][0],
'placeholder':page.placeholders.get(slot="body").pk,
}
response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data)
self.assertEquals(response.status_code, 200)
self.assertEquals(int(response.content), CMSPlugin.objects.all()[0].pk)
# there should be only 1 plugin
self.assertEquals(CMSPlugin.objects.all().count(), 1)
ph = Placeholder(slot="subplugin")
ph.save()
plugin_data = {
'plugin_type':"TextPlugin",
'language':settings.LANGUAGES[0][0],
'placeholder': ph.pk,
'parent': int(response.content)
}
response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data)
# no longer allowed for security reasons
self.assertEqual(response.status_code, 404)
0
Example 84
Project: django-easymode Source File: languagecode.py
def fix_language_code(url, current_language):
"""
Fixes the language code as follows:
If there is only one language used in the site, it strips the language code.
If there are more languages used, it will make sure that the url has the current
language as a prefix.
>>> # multiple languages defined
>>> settings.LANGUAGES = (('en-us','English'),('de','German'),('nl-be','Belgium dutch'),('fr-be','Belgium french'),)
>>> settings.USE_SHORT_LANGUAGE_CODES = False
>>> activate('en-us')
>>> fix_language_code('/de/example.html', 'en-us')
'/en-us/example.html'
>>> settings.USE_SHORT_LANGUAGE_CODES = True
>>> fix_language_code('/de/example.html', 'en-us')
'/en/example.html'
>>> fix_language_code('/en/example.html', 'en-us')
'/example.html'
>>> # only one language defined
>>> settings.LANGUAGES = (('en-us', 'English'), )
>>> fix_language_code('/en-us/example.html', 'en-us')
'/example.html'
:param url: The (absolute) url to be fixed eg. '/hi/how/is/it'.
:param current_language: A language code defined in ``settings.LANGUAGES``.
:rtype: The fixed url.
"""
stripped_url = strip_language_code(url)
if not getattr(settings, 'MASTER_SITE', False) and len(settings.LANGUAGES) == 1:
# no MASTER_SITE and only one language, do not add language code to url
return stripped_url
# add the language code to the url
return u"/%s%s" % (get_shorthand_from_language_code(current_language), stripped_url)
0
Example 85
def get_language_config(content_language=None):
language = get_language()[:2]
if content_language:
content_language = content_language[:2]
else:
content_language = language
config = {}
config['language'] = language
lang_names = SortedDict()
for lang, name in settings.LANGUAGES:
if lang[:2] not in lang_names:
lang_names[lang[:2]] = []
lang_names[lang[:2]].append(_(name))
sp_langs = []
for lang, names in lang_names.items():
if lang == content_language:
default = '+'
else:
default = ''
sp_langs.append('%s%s=%s' % (default, ' / '.join(names), lang))
config['spellchecker_languages'] = ','.join(sp_langs)
if content_language in settings.LANGUAGES_BIDI:
config['directionality'] = 'rtl'
else:
config['directionality'] = 'ltr'
if tinymce_settings.USE_SPELLCHECKER:
config['spellchecker_rpc_url'] = reverse('tinymce.views.spell_check')
return config
0
Example 86
@lru_cache.lru_cache(maxsize=1000)
def get_supported_language_variant(lang_code, strict=False):
"""
Returns the language-code that's listed in supported languages, possibly
selecting a more generic variant. Raises LookupError if nothing found.
If `strict` is False (the default), the function will look for an alternative
country-specific variant when the currently checked is not found.
lru_cache should have a maxsize to prevent from memory exhaustion attacks,
as the provided language codes are taken from the HTTP request. See also
<https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>.
"""
global _supported
if _supported is None:
from django.conf import settings
_supported = OrderedDict(settings.LANGUAGES)
if lang_code:
# some browsers use deprecated language codes -- #18419
replacement = _BROWSERS_DEPRECATED_LOCALES.get(lang_code)
if lang_code not in _supported and replacement in _supported:
return replacement
# if fr-ca is not supported, try fr.
generic_lang_code = lang_code.split('-')[0]
for code in (lang_code, generic_lang_code):
if code in _supported and check_for_language(code):
return code
if not strict:
# if fr-fr is not supported, try fr-ca.
for supported_code in _supported:
if supported_code.startswith(generic_lang_code + '-'):
return supported_code
raise LookupError(lang_code)
0
Example 87
def get_model(self, options):
@python_2_unicode_compatible
class PathMetadataBase(MetadataBaseModel):
_path = models.CharField(
_('path'),
max_length=255,
)
if options.use_sites:
_site = models.ForeignKey(
Site,
null=True,
blank=True,
verbose_name=_("site"),
)
if options.use_i18n:
_language = models.CharField(
_("language"),
max_length=5,
null=True,
blank=True,
db_index=True,
choices=settings.LANGUAGES,
)
objects = self.get_manager(options)()
def __str__(self):
return self._path
def _process_context(self, context):
self.__context = context.get('view_context')
def _populate_from_kwargs(self):
return {'path': self._path}
def _resolve_value(self, name):
value = super(PathMetadataBase, self)._resolve_value(name)
try:
return self._resolve_template(value,
context=self.__context)
except AttributeError:
return value
class Meta:
abstract = True
unique_together = self.get_unique_together(options)
return PathMetadataBase
0
Example 88
def process_request(self, request):
"""Process the request of according to following conditions:
- Only processes ``GET`` request, since others will not be displayed in the address bar anyway
- Only processes ``GET`` request for url path's (as regular expressions) which are provided in ``URLI18N_INCLUDE_PATHS`` setting. If a path is provided in ``URLI18N_INCLUDE_PATHS`` setting it will transform the url, for all others the url will not be transformed (though the language will be changed)
- If the url path does not start with a language prefix and it will build a new url from given path and redirect to it
- If ``URLI18N_ALWAYS_SHOW_LANGUAGE`` setting is set to True (the default) it will always show the language prefix in the url, if ``URLI18N_ALWAYS_SHOW_LANGUAGE`` setting is set to False it will show the language prefix only for languages which are not the default language (set via the django setting for ``LANGUAGE_CODE``)
- If url path starts with a valid language prefix it will render the view attached to the given url in the original url conf. If will resolve other middleware classes ``process_request`` and ``process_view`` calls first to avoid conflicts
- If user is not navigating on the page but coming from a source which is not the domain of this project it will change the language directly when provided in the url or if not provided use the current activated language (given by process_request of django.middleware.locale.LocaleMiddleware)
Args:
- ``request``: the django request object to process
Returns:
- Either a redirect response to the right path with leading language shortcut or the view response for the view attached to the url of the path
"""
if request.method == 'GET':
path = request.path
full_path = request.get_full_path()
language = translation.get_language()
host = request.get_host()
redirect_to = None
regex_ref = re.compile('^http[s]?://%s' % host, re.UNICODE)
referer = request.META.get('HTTP_REFERER', None)
language_shortcuts = [lang[0] for lang in settings.LANGUAGES]
if utils.is_included_path(path) and utils.show_language(language):
#redirect to the url with the appropriate language shortcut
return shortcuts.redirect('/%s%s' % (language, full_path))
regex_prefix = re.compile('^/[-\w]+/')
language_from_path = regex_prefix.findall(path)
if language_from_path:
language_from_path = language_from_path[0].replace('/','')
if not referer or regex_ref.match(referer) is None:
if language_from_path in language_shortcuts and language_from_path!=language:
translation.activate(language_from_path)
request.LANGUAGE_CODE = translation.get_language()
language = translation.get_language()
if language_from_path in language_shortcuts and language_from_path!=language:
#cut of the language shortcut
path = path.replace('/%s' % language_from_path, '', 1)
full_path = full_path.replace('/%s' % language_from_path, '', 1)
#check if the path is_included_path
if utils.is_included_path(path):
#redirect to the url with the appropriate language shortcut
if utils.show_language(language):
return shortcuts.redirect('/%s%s' % (language, full_path))
else:
return shortcuts.redirect('%s' % full_path)
elif language_from_path==language and utils.show_language(language):
path = path.replace('/%s' % language_from_path, '', 1)
full_path = full_path.replace('/%s' % language_from_path, '', 1)
#check if the path is_included_path
if utils.is_included_path(path):
#render the view
#all the other middleware's following this middleware in
#settings MIDDLEWARE_CLASSES still need to be
#processed (process_request) + all Middleware's inside
#of settings MIDDLEWARE_CLASSES process_view
#methods need to be processed as well before actually
#returning the view here
view, args, kwargs = urlresolvers.resolve(path)
process_request_result = utils.process_missing_requests(self, request)
if process_request_result is not None:
return process_request_result
process_request_view = utils.process_missing_views(self, request, view, args, kwargs)
if process_request_view is not None:
return process_request_view
return view(request, *args, **kwargs)
0
Example 89
def get_model(self, options):
@python_2_unicode_compatible
class ViewMetadataBase(MetadataBaseModel):
__context = None
_view = models.CharField(
_('view'),
max_length=255,
default="",
blank=True,
)
if options.use_sites:
_site = models.ForeignKey(
Site,
null=True,
blank=True,
verbose_name=_("site"),
)
if options.use_i18n:
_language = models.CharField(
_("language"),
max_length=5,
null=True,
blank=True,
db_index=True,
choices=settings.LANGUAGES,
)
objects = self.get_manager(options)()
def _process_context(self, context):
"""Use the context when rendering any substitutions."""
self.__context = context.get('view_context')
def _populate_from_kwargs(self):
return {'view_name': self._view}
def _resolve_value(self, name):
value = super(ViewMetadataBase, self)._resolve_value(name)
try:
return self._resolve_template(value,
context=self.__context)
except AttributeError:
return value
def __str__(self):
return self._view
class Meta:
abstract = True
unique_together = self.get_unique_together(options)
return ViewMetadataBase
0
Example 90
def handle(self, *args, **options):
"""
Migrate database settings for labels, descriptions, and other text
into .po message files.
"""
self.setup_logging(int(options.get('verbosity')))
# Use the specified locale, or if none are provided, use all defined in settings
locale = options.get("locale")
locales = [locale] if locale else [l[0] for l in settings.LANGUAGES]
# Make messages for each available locale
for locale in locales:
logger.info('Processing locale %(locale)s', {'locale':locale})
poutil = PoUtils(locale)
for region in Region.objects.all():
# The short label of the region
poutil.add_or_update(
msgid=u'%s short label' % region.name,
msgstr=region.label
)
# The label of the region
poutil.add_or_update(
msgid=u'%s label' % region.name,
msgstr=region.label
)
# The long description of the region
poutil.add_or_update(
msgid=u'%s long description' % region.name,
msgstr=region.description
)
for legislativebody in region.legislativebody_set.all():
# The short label for all districts in this body
poutil.add_or_update(
msgid=u'%s short label' % legislativebody.name,
msgstr=legislativebody.short_label.replace('%s', '%(district_id)s')
)
# The label for all districts in this body
poutil.add_or_update(
msgid=u'%s label' % legislativebody.name,
msgstr=legislativebody.long_label.replace('%s', '%(district_id)s')
)
# The description for all districts in this body (unused)
poutil.add_or_update(
msgid=u'%s long description' % legislativebody.name,
msgstr=legislativebody.title
)
for geolevel in Geolevel.objects.all():
# The short label of the geolevel
poutil.add_or_update(
msgid=u'%s short label' % geolevel.name,
msgstr=geolevel.label
)
# The label of the geolevel
poutil.add_or_update(
msgid=u'%s label' % geolevel.name,
msgstr=geolevel.label
)
# The long description of the geolevel (unused)
poutil.add_or_update(
msgid=u'%s long description' % geolevel.name,
msgstr=''
)
for scoredisplay in ScoreDisplay.objects.all():
# The short label of the score display
poutil.add_or_update(
msgid=u'%s short label' % scoredisplay.name,
msgstr=scoredisplay.title
)
# The label of the score display
poutil.add_or_update(
msgid=u'%s label' % scoredisplay.name,
msgstr=scoredisplay.title
)
# The long description of the score display (unused)
poutil.add_or_update(
msgid=u'%s long description' % scoredisplay.name,
msgstr=''
)
for scorefunction in ScoreFunction.objects.all():
# The short label of the score function
poutil.add_or_update(
msgid=u'%s short label' % scorefunction.name,
msgstr=scorefunction.label
)
# The label of the score function
poutil.add_or_update(
msgid=u'%s label' % scorefunction.name,
msgstr=scorefunction.label
)
# The long description of the score function
poutil.add_or_update(
msgid=u'%s long description' % scorefunction.name,
msgstr=scorefunction.description
)
for scorepanel in ScorePanel.objects.all():
# The short label of the score panel
poutil.add_or_update(
msgid=u'%s short label' % scorepanel.name,
msgstr=scorepanel.title
)
# The label of the score panel
poutil.add_or_update(
msgid=u'%s label' % scorepanel.name,
msgstr=scorepanel.title
)
# The long description of the score panel
poutil.add_or_update(
msgid=u'%s long description' % scorepanel.name,
msgstr=''
)
for subject in Subject.objects.all():
# The short label of the subject
poutil.add_or_update(
msgid=u'%s short label' % subject.name,
msgstr=subject.short_display
)
# The label of the subject
poutil.add_or_update(
msgid=u'%s label' % subject.name,
msgstr=subject.display
)
# The long description of the subject
poutil.add_or_update(
msgid=u'%s long description' % subject.name,
msgstr=subject.description
)
for validationcriterion in ValidationCriteria.objects.all():
# The short label of the validation criterion
poutil.add_or_update(
msgid=u'%s short label' % validationcriterion.name,
msgstr=validationcriterion.title
)
# The label of the validation criterion
poutil.add_or_update(
msgid=u'%s label' % validationcriterion.name,
msgstr=validationcriterion.title
)
# The long description of the validation criterion
poutil.add_or_update(
msgid=u'%s long description' % validationcriterion.name,
msgstr=validationcriterion.description
)
poutil.save()
0
Example 91
def get_language_from_request(request, check_path=False):
"""
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.
If check_path is True, the URL path prefix will be checked for a language
code, otherwise this is skipped for backwards compatibility.
"""
from django.conf import settings
global _supported
if _supported is None:
_supported = OrderedDict(settings.LANGUAGES)
if check_path:
lang_code = get_language_from_path(request.path_info)
if lang_code is not None:
return lang_code
if hasattr(request, 'session'):
# for backwards compatibility django_language is also checked (remove in 1.8)
lang_code = request.session.get(LANGUAGE_SESSION_KEY, request.session.get('django_language'))
if lang_code in _supported and lang_code is not None and check_for_language(lang_code):
return lang_code
lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)
try:
return get_supported_language_variant(lang_code)
except LookupError:
pass
accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
for accept_lang, unused in parse_accept_lang_header(accept):
if accept_lang == '*':
break
if not language_code_re.search(accept_lang):
continue
try:
return get_supported_language_variant(accept_lang)
except LookupError:
continue
try:
return get_supported_language_variant(settings.LANGUAGE_CODE)
except LookupError:
return settings.LANGUAGE_CODE
0
Example 92
def get_model(self, options):
@python_2_unicode_compatible
class ModelInstanceMetadataBase(MetadataBaseModel):
_path = models.CharField(
_('path'),
max_length=255,
blank=True,
editable=False,
)
_content_type = models.ForeignKey(
ContentType,
verbose_name=_("model"),
)
_object_id = models.PositiveIntegerField(
verbose_name=_("ID"),
)
_content_object = GenericForeignKey('_content_type', '_object_id')
if options.use_sites:
_site = models.ForeignKey(
Site,
null=True,
blank=True,
verbose_name=_("site"),
)
if options.use_i18n:
_language = models.CharField(
_("language"),
max_length=5,
null=True,
blank=True,
db_index=True,
choices=settings.LANGUAGES
)
objects = self.get_manager(options)()
def __str__(self):
return self._path
class Meta:
unique_together = self.get_unique_together(options)
abstract = True
def _process_context(self, context):
self.__context = context.get('view_context')
context['content_type'] = self._content_type
context['model_instance'] = self
def _populate_from_kwargs(self):
return {'model_instance': self._content_object}
def _resolve_value(self, name):
value = super(ModelInstanceMetadataBase, self)._resolve_value(
name)
try:
return self._resolve_template(value, self._content_object,
context=self.__context)
except AttributeError:
return value
def save(self, *args, **kwargs):
try:
path_func = self._content_object.get_absolute_url
except AttributeError:
pass
else:
self._path = path_func()
try:
super(ModelInstanceMetadataBase, self).save(*args,
**kwargs)
except IntegrityError:
pass
return ModelInstanceMetadataBase
0
Example 93
def get_model(self, options):
@python_2_unicode_compatible
class ModelMetadataBase(MetadataBaseModel):
__instance = None
__context = None
_content_type = models.ForeignKey(
ContentType,
verbose_name=_("model"),
)
if options.use_sites:
_site = models.ForeignKey(
Site,
null=True,
blank=True,
verbose_name=_("site"),
)
if options.use_i18n:
_language = models.CharField(
_("language"),
max_length=5,
null=True,
blank=True,
db_index=True,
choices=settings.LANGUAGES,
)
objects = self.get_manager(options)()
def __str__(self):
return str(self._content_type)
def _process_context(self, context):
""" Use the given model instance as context for rendering
any substitutions.
"""
self.__instance = context.get('model_instance')
self.__context = context.get('view_context')
def _populate_from_kwargs(self):
return {'content_type': self._content_type}
def _resolve_value(self, name):
value = super(ModelMetadataBase, self)._resolve_value(name)
content_object = getattr(self.__instance, '_content_object',
None)
return self._resolve_template(value, content_object,
context=self.__context)
class Meta:
abstract = True
unique_together = self.get_unique_together(options)
return ModelMetadataBase
0
Example 94
Project: pycontw2016 Source File: test_views.py
def language_gen():
from django.conf import settings
for lang_code, _ in settings.LANGUAGES:
yield lang_code
0
Example 95
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
0
Example 96
Project: django-multilingual-search Source File: test_hooks.py
@mock.patch('elasticsearch.Elasticsearch')
def test_post_save_and_delete_hook(self, es_obj):
# index uses a global loader for the backend.
docuements = create_docuements()
doc = docuements[0]
doc.save()
# send the post_save signal
index = haystack.connections['default'].get_unified_index().get_index(Docuement)
backend = index._get_backend('default') # Multilingual Backend
# test if the command has been sent to ES
if not isinstance(backend.conn, mock.Mock):
backend.conn = mock.MagicMock()
es = backend.conn
index.update_object(doc.object, 'default')
self.assertFalse(es.delete.called)
self.assertTrue(es.bulk.called)
call_args = es.bulk.call_args_list
self.assertEqual(len(call_args), len(settings.LANGUAGES))
self.assertEqual(call_args[0][0][0][0], {'index': {'_id': 'testproject.docuement.1'}})
index_list = [a[1] for a in call_args]
self.assertIn({'doc_type': 'modelresult', 'index': 'testproject-en'}, index_list)
self.assertIn({'doc_type': 'modelresult', 'index': 'testproject-de'}, index_list)
self.assertIn({'doc_type': 'modelresult', 'index': 'testproject-es'}, index_list)
self.assertIn(doc.object.text_en, call_args[0][0][0][1]['text'])
# test delete
index.remove_object(doc.object, 'default')
self.assertTrue(es.delete.called)
call_args = es.delete.call_args_list
self.assertEqual(len(call_args), len(settings.LANGUAGES))
self.assertEqual(call_args[0][1],
{'index': 'testproject-en', 'ignore': 404,
'doc_type': 'modelresult', 'id': 'testproject.docuement.1'})
self.assertEqual(call_args[1][1],
{'id': 'testproject.docuement.1', 'doc_type': 'modelresult',
'ignore': 404, 'index': 'testproject-de'})
0
Example 97
def get_language_from_request(request, check_path=False):
"""
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.
If check_path is True, the URL path prefix will be checked for a language
code, otherwise this is skipped for backwards compatibility.
"""
global _accepted
from django.conf import settings
supported = dict(settings.LANGUAGES)
if check_path:
lang_code = get_language_from_path(request.path_info, supported)
if lang_code is not None:
return lang_code
if hasattr(request, 'session'):
lang_code = request.session.get('django_language', None)
if lang_code in supported and lang_code is not None and check_for_language(lang_code):
return lang_code
lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME)
if lang_code and lang_code not in supported:
lang_code = lang_code.split('-')[0] # e.g. if fr-ca is not supported fallback to fr
if lang_code and lang_code in supported and check_for_language(lang_code):
return lang_code
accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
for accept_lang, unused in parse_accept_lang_header(accept):
if accept_lang == '*':
break
# We have a very restricted form for our language files (no encoding
# specifier, since they all must be UTF-8 and only one possible
# language each time. So we avoid the overhead of gettext.find() and
# work out the MO file manually.
# 'normalized' is the root name of the locale in POSIX format (which is
# the format used for the directories holding the MO files).
normalized = locale.locale_alias.get(to_locale(accept_lang, True))
if not normalized:
continue
# Remove the default encoding from locale_alias.
normalized = normalized.split('.')[0]
if normalized in _accepted:
# We've seen this locale before and have an MO file for it, so no
# need to check again.
return _accepted[normalized]
for lang, dirname in ((accept_lang, normalized),
(accept_lang.split('-')[0], normalized.split('_')[0])):
if lang.lower() not in supported:
continue
for path in all_locale_paths():
if os.path.exists(os.path.join(path, dirname, 'LC_MESSAGES', 'django.mo')):
_accepted[normalized] = lang
return lang
return settings.LANGUAGE_CODE
0
Example 98
def handle(self, *args, **options):
"""
Create and compile language message files
"""
# Execute every action if either all or none of the options are specified
everything = options.get("templates") == options.get("javascript") == options.get("compile")
# Use the specified locale, or if none are provided, use all defined in settings
locale = options.get("locale")
locales = [locale] if locale else [l[0] for l in settings.LANGUAGES]
# Make messages for each available locale
for locale in locales:
# Make messages for templates (.html, .txt, .email)
if everything or options.get("templates"):
management.call_command('makemessages',
locale=locale,
extensions=['html','txt','email'],
interactive=False,
verbosity=options.get('verbosity'),
ignore_patterns=[ 'static-media/jquery/*.*']
)
# Make messages for javascript
if everything or options.get("javascript"):
management.call_command('makemessages',
locale=locale,
domain='djangojs',
interactive=False,
verbosity=options.get('verbosity'),
ignore_patterns=[ 'static-media*' ]
)
# Compile message file
if everything or options.get("compile"):
management.call_command('compilemessages',
locale=locale,
interactive=False,
verbosity=options.get('verbosity')
)
0
Example 99
Project: cmsplugin-rt Source File: plugins.py
def test_remove_plugin_after_published(self):
# add a page
page_data = self.get_new_page_data()
response = self.client.post(URL_CMS_PAGE_ADD, page_data)
page = Page.objects.all()[0]
# add a plugin
plugin_data = {
'plugin_type':"TextPlugin",
'language':settings.LANGUAGES[0][0],
'placeholder':page.placeholders.get(slot="body").pk,
}
response = self.client.post(URL_CMS_PLUGIN_ADD, plugin_data)
plugin_id = int(response.content)
self.assertEquals(response.status_code, 200)
self.assertEquals(int(response.content), CMSPlugin.objects.all()[0].pk)
# there should be only 1 plugin
self.assertEquals(CMSPlugin.objects.all().count(), 1)
# publish page
response = self.client.post(URL_CMS_PAGE + "%d/change-status/" % page.pk, {1 :1})
self.assertEqual(response.status_code, 200)
# there should now be two plugins - 1 draft, 1 public
self.assertEquals(CMSPlugin.objects.all().count(), 2)
# delete the plugin
plugin_data = {
'plugin_id': plugin_id
}
remove_url = URL_CMS_PLUGIN_REMOVE
response = self.client.post(remove_url, plugin_data)
self.assertEquals(response.status_code, 200)
# there should be no plugins
self.assertEquals(CMSPlugin.objects.all().count(), 0)
0
Example 100
Project: shuup Source File: test_multilanguage_model_form.py
@pytest.mark.django_db
@override_settings(**{"LANGUAGES": (("en", "en"), ("fi", "fi"), ("ja", "ja")), "PARLER_DEFAULT_LANGUAGE_CODE": "en"})
def test_model_form_partially_translated():
activate("en")
request = RequestFactory().get("/")
test_name_en = "Test shop"
payment_method = get_default_payment_method()
payment_method.name = test_name_en
payment_method.save()
form = PaymentMethodForm(instance=payment_method, request=request, languages=settings.LANGUAGES)
data = get_form_data(form, prepared=True)
assert data.get("name__en") == test_name_en
assert not data.get("name__fi")
form = PaymentMethodForm(data=data, instance=payment_method, request=request, languages=settings.LANGUAGES)
form.full_clean()
assert form.is_valid() and not form.errors
payment_method = form.save()
# Add description for Finnish and and name in Finnish should be required
data["description__fi"] = "Some description"
form = PaymentMethodForm(data=data, instance=payment_method, request=request, languages=settings.LANGUAGES)
form.full_clean()
assert not form.is_valid() and form.errors
test_name_fi = "Some method name in finnish"
data["name__fi"] = test_name_fi
form = PaymentMethodForm(data=data, instance=payment_method, request=request, languages=settings.LANGUAGES)
form.full_clean()
assert form.is_valid() and not form.errors
payment_method = form.save()
assert payment_method.name == test_name_en, "Object in English"
activate("fi")
payment_method.set_current_language("fi")
assert payment_method.name == test_name_fi, "Object in Finnish"
activate("ja")
payment_method.set_current_language("ja")
assert payment_method.name == test_name_en, "Should fallback to English"
# Check that no sneaky translations is not created for Japan
with pytest.raises(ObjectDoesNotExist):
translation = payment_method.get_translation("ja")
translation.refresh_from_db() # Just in case if the translation object comes from cache or something
# Empty finnish translations and see if Finnish starts fallbacks too
data["name__fi"] = data["description__fi"] = ""
form = PaymentMethodForm(data=data, instance=payment_method, request=request, languages=settings.LANGUAGES)
form.full_clean()
assert form.is_valid() and not form.errors
form.save()
# Check that no sneaky translations is not created for Finnish
with pytest.raises(ObjectDoesNotExist):
translation = payment_method.get_translation("fi")
translation.refresh_from_db() # Just in case if the translation object comes from cache or something