Skip to content

Commit

Permalink
Merge pull request #2 from digi604/new_i18n_settings
Browse files Browse the repository at this point in the history
New i18n settings
  • Loading branch information
digi604 committed Oct 3, 2012
2 parents b6fde0a + a6f90d1 commit a204712
Show file tree
Hide file tree
Showing 33 changed files with 628 additions and 322 deletions.
13 changes: 4 additions & 9 deletions cms/admin/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from cms.forms.widgets import UserSelectAdminWidget
from cms.models import (Page, PagePermission, PageUser, ACCESS_PAGE,
PageUserGroup)
from cms.utils.i18n import get_language_tuple, get_language_list
from cms.utils.mail import mail_page_user_change
from cms.utils.page import is_valid_page_slug
from cms.utils.page_resolver import get_page_from_path, is_valid_url
Expand Down Expand Up @@ -60,7 +61,7 @@ class PageAddForm(forms.ModelForm):
help_text=_('The default title'))
slug = forms.CharField(label=_("Slug"), widget=forms.TextInput(),
help_text=_('The part of the title that is used in the URL'))
language = forms.ChoiceField(label=_("Language"), choices=settings.CMS_LANGUAGES,
language = forms.ChoiceField(label=_("Language"), choices=get_language_tuple(),
help_text=_('The current language of the content fields.'))

class Meta:
Expand All @@ -74,13 +75,7 @@ def __init__(self, *args, **kwargs):
if not self.fields['site'].initial:
self.fields['site'].initial = Site.objects.get_current().pk
site_id = self.fields['site'].initial
languages = []
language_mappings = dict(settings.LANGUAGES)
if site_id in settings.CMS_SITE_LANGUAGES:
for lang in settings.CMS_SITE_LANGUAGES[site_id]:
languages.append((lang, language_mappings.get(lang, lang)))
else:
languages = settings.CMS_LANGUAGES
languages = get_language_tuple(site_id)
self.fields['language'].choices = languages
if not self.fields['language'].initial:
self.fields['language'].initial = get_language()
Expand Down Expand Up @@ -142,7 +137,7 @@ def clean_slug(self):

def clean_language(self):
language = self.cleaned_data['language']
if not language in dict(settings.CMS_LANGUAGES).keys():
if not language in get_language_list():
raise ValidationError("Given language does not match language settings.")
return language

Expand Down
24 changes: 7 additions & 17 deletions cms/admin/pageadmin.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from cms.utils import (copy_plugins, helpers, moderator, permissions, plugins,
get_template_from_request, get_language_from_request,
placeholder as placeholder_utils, admin as admin_utils, cms_static_url)
from cms.utils.i18n import get_language_dict, get_language_list, get_language_tuple, get_language_object
from cms.utils.page_resolver import is_valid_url
from cms.utils.admin import jsonify_request
from cms.utils.permissions import has_plugin_permission
Expand Down Expand Up @@ -441,13 +442,13 @@ def get_form(self, request, obj=None, **kwargs):
installed_plugins = plugin_pool.get_all_plugins(placeholder_name, obj)
plugin_list = CMSPlugin.objects.filter(language=language, placeholder=placeholder, parent=None).order_by('position')
other_plugins = CMSPlugin.objects.filter(placeholder=placeholder, parent=None).exclude(language=language)
dict_cms_languages = dict(settings.CMS_LANGUAGES)
dict_cms_languages = get_language_dict()
for plugin in other_plugins:
if (not plugin.language in copy_languages) and (plugin.language in dict_cms_languages):
copy_languages[plugin.language] = dict_cms_languages[plugin.language]

language = get_language_from_request(request, obj)
if copy_languages and len(settings.CMS_LANGUAGES) > 1:
if copy_languages and len(get_language_list()) > 1:
show_copy = True
widget = PluginEditor(attrs={
'installed': installed_plugins,
Expand Down Expand Up @@ -565,14 +566,7 @@ def _get_site_languages(self, obj):
site_id = None
if obj:
site_id = obj.site_id
languages = []
if site_id and site_id in settings.CMS_SITE_LANGUAGES:
for lang in settings.CMS_SITE_LANGUAGES[site_id]:
lang_label = dict(settings.CMS_LANGUAGES).get(lang, dict(settings.LANGUAGES).get(lang, lang))
languages.append((lang, lang_label))
else:
languages = settings.CMS_LANGUAGES
return languages
return get_language_tuple(site_id)

def update_language_tab_context(self, request, obj, context=None):
if not context:
Expand Down Expand Up @@ -675,11 +669,7 @@ def changelist_view(self, request, extra_context=None):
site_id = int(site_id)

# languages
languages = []
if site_id and site_id in settings.CMS_SITE_LANGUAGES:
languages = settings.CMS_SITE_LANGUAGES[site_id]
else:
languages = [lang[0] for lang in settings.CMS_LANGUAGES]
languages = get_language_list(site_id)

# parse the cookie that saves which page trees have
# been opened already and extracts the page ID
Expand Down Expand Up @@ -985,7 +975,7 @@ def delete_translation(self, request, object_id, extra_context=None):
raise PermissionDenied

message = _('Title and plugins with language %(language)s was deleted') % {
'language': [name for code, name in settings.CMS_LANGUAGES if code == language][0]
'language': get_language_object(language)['name']
}
self.log_change(request, titleobj, message)
self.message_user(request, message)
Expand Down Expand Up @@ -1188,7 +1178,7 @@ def copy_plugins(self, request):

if not page.has_change_permission(request):
return HttpResponseForbidden(ugettext("You do not have permission to change this page"))
if not language or not language in [ lang[0] for lang in settings.CMS_LANGUAGES ]:
if not language or not language in get_language_list():
return HttpResponseBadRequest(ugettext("Language must be set to a supported language!"))
if language == copy_from:
return HttpResponseBadRequest(ugettext("Language must be different than the copied language!"))
Expand Down
5 changes: 3 additions & 2 deletions cms/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
calling these methods!
"""
import datetime
from cms.utils.i18n import get_language_list

from django.conf import settings
from django.contrib.auth.models import User
Expand Down Expand Up @@ -125,7 +126,7 @@ def create_page(title, template, language, menu_title=None, slug=None,
assert template in [tpl[0] for tpl in settings.CMS_TEMPLATES]

# validate language:
assert language in [lang[0] for lang in settings.CMS_LANGUAGES]
assert language in get_language_list()

# set default slug:
if not slug:
Expand Down Expand Up @@ -220,7 +221,7 @@ def create_title(language, title, page, menu_title=None, slug=None,
See docs/extending_cms/api_reference.rst for more info
"""
# validate language:
assert language in [lang[0] for lang in settings.CMS_LANGUAGES]
assert language in get_language_list()

# validate page
assert isinstance(page, Page)
Expand Down
4 changes: 2 additions & 2 deletions cms/appresolver.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import with_statement
from cms.apphook_pool import apphook_pool
from cms.utils.i18n import force_language
from cms.utils.i18n import force_language, get_language_list
from cms.utils.moderator import get_page_queryset

from django.conf import settings
Expand Down Expand Up @@ -31,7 +31,7 @@ def applications_page_check(request, current_page=None, path=None):
# This removes the non-CMS part of the URL.
path = request.path.replace(reverse('pages-root'), '', 1)
# check if application resolver can resolve this
for lang, lang_name in settings.CMS_LANGUAGES:
for lang in get_language_list():
if path.startswith(lang+"/"):
path = path[len(lang+"/"):]
for resolver in APP_RESOLVERS:
Expand Down
11 changes: 7 additions & 4 deletions cms/conf/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from cms.exceptions import CMSDeprecationWarning
from django.conf import settings
from patch import post_patch, post_patch_check
from patch import post_patch, post_patch_check, pre_patch
import warnings


Expand All @@ -9,21 +10,23 @@ def patch_settings():
"""Merge settings with global cms settings, so all required attributes
will exist. Never override, just append non existing settings.
Also check for setting inconstistence if settings.DEBUG
Also check for setting inconsistencies if settings.DEBUG
"""
if patch_settings.ALREADY_PATCHED:
return
patch_settings.ALREADY_PATCHED = True

if getattr(settings, 'CMS_FLAT_URLS', False):
warnings.warn("CMS_FLAT_URLS are deprecated and will be removed in django CMS 2.4!", DeprecationWarning)
warnings.warn("CMS_FLAT_URLS are deprecated and will be removed in django CMS 2.4!", CMSDeprecationWarning)

if getattr(settings, 'CMS_MODERATOR', False):
warnings.warn("CMS_MODERATOR will be removed and replaced in django CMS 2.4!", DeprecationWarning)
warnings.warn("CMS_MODERATOR will be removed and replaced in django CMS 2.4!", CMSDeprecationWarning)

from cms.conf import global_settings
# patch settings

pre_patch()

# merge with global cms settings
for attr in dir(global_settings):
if attr == attr.upper() and not hasattr(settings, attr):
Expand Down
53 changes: 32 additions & 21 deletions cms/conf/global_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,34 +70,45 @@
# Wheter the cms has a softroot functionionality
CMS_SOFTROOT = False

#Hide untranslated Pages
CMS_HIDE_UNTRANSLATED = True

#Fall back to another language if the requested page isn't available in the preferred language
CMS_LANGUAGE_FALLBACK = True

#Configuration on how to order the fallbacks for languages.
# example: {'de': ['en', 'fr'],
# 'en': ['de'],
# }
CMS_LANGUAGE_CONF = {}
# Defines which languages should be offered and what are the defaults
# example:
# CMS_LANGUAGES = {
# 1: [
# {
# 'code': 'en',
# 'name': _('English'),
# 'fallbacks': ['de', 'fr'],
# 'public': True,
# 'hide_untranslated': True,
# 'redirect_on_fallback':False,
# },
# {
# 'code': 'de',
# 'name': _('Deutsch'),
# 'fallbacks': ['en', 'fr'],
# 'public': True,
# },
# {
# 'code': 'fr',
# 'public': False,
# }
# ],
# 'default': {
# 'fallbacks': ['en', 'de', 'fr'],
# 'redirect_on_fallback':True,
# 'public': False,
# 'hide_untranslated': False,
# }
#}

#CMS_LANGUAGES = {}

# Defines which languages should be offered.
CMS_LANGUAGES = settings.LANGUAGES

# If you have different sites with different languages you can configure them here
# and you will only be able to edit the languages that are actually on the site.
# example: {1:['en','de'],
# 2:['en','fr'],
# 3:['en'],}
CMS_SITE_LANGUAGES = {}

CMS_SITE_CHOICES_CACHE_KEY = 'CMS:site_choices'
CMS_PAGE_CHOICES_CACHE_KEY = 'CMS:page_choices'

# Languages that are visible in the frontend (Language Chooser)
CMS_FRONTEND_LANGUAGES = [x[0] for x in CMS_LANGUAGES]


# Path for CMS media (uses <MEDIA_ROOT>/cms by default)
CMS_MEDIA_PATH = 'cms/'
Expand Down
123 changes: 122 additions & 1 deletion cms/conf/patch.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
# -*- coding: utf-8 -*-
from cms.exceptions import CMSDeprecationWarning
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import ugettext_lazy as _
from sekizai.helpers import validate_template
import warnings

def pre_patch():
"""Patch settings for dynamic defaults"""
if not getattr(settings, 'CMS_LANGUAGES', False):
settings.CMS_LANGUAGES = {settings.SITE_ID:[]}
for code, name in settings.LANGUAGES:
lang = {'code':code, 'name':_(name)}
settings.CMS_LANGUAGES[settings.SITE_ID].append(lang)

def post_patch():
"""Patch settings after global are adde
"""Patch settings after global are added
"""
if settings.CMS_TEMPLATE_INHERITANCE:
# Append the magic inheritance template
Expand Down Expand Up @@ -46,3 +55,115 @@ def post_patch_check():
"I can't find the namespaces in %r."
% template[0]
)
VALID_LANG_PROPS = ['code', 'name', 'fallbacks', 'hide_untranslated', 'redirect_on_fallback', 'public']
try:
for site in settings.CMS_LANGUAGES:
try:
int(site)
except ValueError:
if not site =="default":
raise ImproperlyConfigured("CMS_LANGUAGES can only be filled with integers (site ids) and 'default'"
" for default values. %s is not a valid key." % site)
for language in settings.CMS_LANGUAGES[site]:
if site == "default":
if language not in VALID_LANG_PROPS:
raise ImproperlyConfigured("CMS_LANGUAGES has an invalid property in the default properties: %(property)s" %
{'property':language})
continue
if not "code" in language.keys():
raise ImproperlyConfigured("CMS_LANGUAGES has a language without a 'code' property")
if not 'name' in language.keys():
raise ImproperlyConfigured("CMS_LANGUAGES has a language without a 'name' property")
for key in language:
if key not in VALID_LANG_PROPS:
raise ImproperlyConfigured("CMS_LANGUAGES has an invalid property on the site %(site)s and "
"language %(language)s: %(property)s" %
{'site':site, 'language':language['code'], 'property':key})
# Fill up the defaults
if not language.has_key('fallbacks'):
fallbacks = []
for tmp_language in settings.CMS_LANGUAGES[site]:
tmp_language = tmp_language.copy()
if not tmp_language.has_key('public'):
if settings.CMS_LANGUAGES.has_key('default'):
tmp_language['public'] = settings.CMS_LANGUAGES['default'].get('public', True)
else:
tmp_language['public'] = True
if tmp_language['public']:
fallbacks.append(tmp_language['code'])
if fallbacks:
fallbacks.remove(language['code'])
if settings.CMS_LANGUAGES.has_key('default'):
language['fallbacks'] = settings.CMS_LANGUAGES['default'].get('fallbacks', fallbacks)
else:
language['fallbacks'] = fallbacks
if not language.has_key('public'):
if settings.CMS_LANGUAGES.has_key('default'):
language['public'] = settings.CMS_LANGUAGES['default'].get('public', True)
else:
language['public'] = True
if not language.has_key('redirect_on_fallback'):
if settings.CMS_LANGUAGES.has_key('default'):
language['redirect_on_fallback'] = settings.CMS_LANGUAGES['default'].get('redirect_on_fallback', True)
else:
language['redirect_on_fallback'] = True
if not language.has_key('hide_untranslated'):
if settings.CMS_LANGUAGES.has_key('default'):
language['hide_untranslated'] = settings.CMS_LANGUAGES['default'].get('hide_untranslated', True)
else:
language['hide_untranslated'] = True
except TypeError:
if type(settings.CMS_LANGUAGES) == tuple:
new_languages = {}
lang_template = {'code':'', 'name':'', 'fallbacks':[],'public':True, 'redirect_on_fallback':True, 'hide_untranslated':False}
if hasattr(settings,'CMS_HIDE_UNTRANSLATED'):
lang_template['hide_untranslated'] = settings.CMS_HIDE_UNTRANSLATED
if hasattr(settings, 'CMS_SITE_LANGUAGES'):
for site in settings.CMS_SITE_LANGUAGES:
new_languages[site] = []
else:
new_languages[1]=[]

if hasattr(settings, 'CMS_SITE_LANGUAGES'):
for site in settings.CMS_SITE_LANGUAGES:
for site_code in settings.CMS_SITE_LANGUAGES[site]:
for code, name in settings.CMS_LANGUAGES:
if code == site_code:
new_languages[site].append(get_old_language_conf(code, name, lang_template))
else:
for code, name in settings.CMS_LANGUAGES:
new_languages[1].append(get_old_language_conf(code, name, lang_template))
settings.CMS_LANGUAGES = new_languages
import pprint
pp = pprint.PrettyPrinter(indent=4)
warnings.warn(
"CMS_LANGUAGES has changed in django-cms 2.4\nYou may replace CMS_LANGUAGES with the following:\n%s" % pp.pformat(settings.CMS_LANGUAGES),
CMSDeprecationWarning)

else:
raise ImproperlyConfigured("CMS_LANGUAGES has changed and has some errors. Please refer to the docs.")


def get_old_language_conf(code, name, template):
language = template.copy()
language['code'] = code
language['name'] = name
default_fallbacks = dict(settings.CMS_LANGUAGES).keys()
if hasattr(settings, 'CMS_LANGUAGE_FALLBACK'):
if settings.CMS_LANGUAGE_FALLBACK:
if hasattr(settings, 'CMS_LANGUAGE_CONF'):
language['fallbacks'] = settings.CMS_LANGUAGE_CONF.get(code, default_fallbacks)
else:
language['fallbacks'] = default_fallbacks
else:
language['fallbacks'] = []
else:
if hasattr(settings, 'CMS_LANGUAGE_CONF'):
language['fallbacks'] = settings.CMS_LANGUAGE_CONF.get(code, default_fallbacks)
else:
language['fallbacks'] = default_fallbacks
if hasattr(settings, 'CMS_FRONTEND_LANGUAGES'):
language['public'] = code in settings.CMS_FRONTEND_LANGUAGES
return language


0 comments on commit a204712

Please sign in to comment.