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
]
python类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
]
test_file_field_form.py 文件源码
项目:django-localized-fields
作者: SectorLabs
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
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)
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