cms.core.translations package¶
Submodules¶
cms.core.translations.admin module¶
-
class
cms.core.translations.admin.
TranslationAdmin
(*args, **kwargs)¶ Bases:
cms.core.translations.admin.TranslationBaseModelAdmin
,django.contrib.admin.options.ModelAdmin
-
get_fieldsets
(request, obj=None)¶
-
get_form
(request, obj=None, **kwargs)¶
-
group_fieldsets
= False¶
-
media
¶
-
-
class
cms.core.translations.admin.
TranslationBaseModelAdmin
(*args, **kwargs)¶ Bases:
django.contrib.admin.options.BaseModelAdmin
-
class
Media
¶ -
css
= {'all': ['//127.0.0.1:8080/static/cms/css/admin/core.translations.fields.css']}¶
-
css_all
= ('core.translations.fields.css',)¶
-
extra
= ''¶
-
js
= ['//127.0.0.1:8080/static/cms/js/admin/core.translations.fields.js']¶
-
url
= 'core.translations.fields.js'¶
-
-
TranslationBaseModelAdmin.
both_empty_values_fields
= ()¶
-
TranslationBaseModelAdmin.
declared_fieldsets
¶
-
TranslationBaseModelAdmin.
formfield_for_dbfield
(db_field, **kwargs)¶
-
TranslationBaseModelAdmin.
get_readonly_fields
(request, obj=None)¶ Hook to specify custom readonly fields.
-
TranslationBaseModelAdmin.
get_translation_field_excludes
(exclude_languages=None)¶ Returns a tuple of translation field names to exclude based on exclude_languages arg. TODO: Currently unused?
-
TranslationBaseModelAdmin.
media
¶
-
TranslationBaseModelAdmin.
patch_translation_field
(db_field, field, **kwargs)¶
-
TranslationBaseModelAdmin.
replace_orig_field
(option)¶ Replaces each original field in option that is registered for translation by its translation fields.
Returns a new list with replaced fields. If option contains no registered fields, it is returned unmodified.
>>> self = TranslationAdmin() # PyFlakes >>> print(self.trans_opts.fields.keys()) ['title',] >>> get_translation_fields(self.trans_opts.fields.keys()[0]) ['title_de', 'title_en'] >>> self.replace_orig_field(['title', 'url']) ['title_de', 'title_en', 'url']
Note that grouped fields are flattened. We do this because:
- They are hard to handle in the jquery-ui tabs implementation
- They don’t scale well with more than a few languages
- It’s better than not handling them at all (okay that’s weak)
>>> self.replace_orig_field((('title', 'url'), 'email', 'text')) ['title_de', 'title_en', 'url_de', 'url_en', 'email_de', 'email_en', 'text']
-
class
-
class
cms.core.translations.admin.
TranslationGenericStackedInline
(*args, **kwargs)¶ Bases:
cms.core.translations.admin.TranslationInlineModelAdmin
,cms.contrib.admin.admin.CMSGenericStackedInline
-
media
¶
-
-
class
cms.core.translations.admin.
TranslationGenericTabularInline
(*args, **kwargs)¶ Bases:
cms.core.translations.admin.TranslationInlineModelAdmin
,cms.contrib.admin.admin.CMSGenericTabularInline
-
media
¶
-
-
class
cms.core.translations.admin.
TranslationInlineModelAdmin
(*args, **kwargs)¶ Bases:
cms.core.translations.admin.TranslationBaseModelAdmin
,django.contrib.admin.options.InlineModelAdmin
-
get_fieldsets
(request, obj=None)¶
-
get_formset
(request, obj=None, **kwargs)¶
-
media
¶
-
-
class
cms.core.translations.admin.
TranslationStackedInline
(*args, **kwargs)¶ Bases:
cms.core.translations.admin.TranslationInlineModelAdmin
,cms.contrib.admin.admin.CMSStackedInline
-
media
¶
-
-
class
cms.core.translations.admin.
TranslationTabularInline
(*args, **kwargs)¶ Bases:
cms.core.translations.admin.TranslationInlineModelAdmin
,cms.contrib.admin.admin.CMSTabularInline
-
media
¶
-
cms.core.translations.apps module¶
cms.core.translations.cms_checks module¶
-
class
cms.core.translations.cms_checks.
CMSChecks
(fail_silently=False)¶ Bases:
cms.utils.cms_check.CMSChecksBase
-
check
()¶
-
cms.core.translations.cms_defaults module¶
cms.core.translations.cms_plugin module¶
cms.core.translations.decorators module¶
cms.core.translations.fields module¶
-
class
cms.core.translations.fields.
LanguageCacheSingleObjectDescriptor
¶ Bases:
object
A Mixin for RelatedObjectDescriptors which use current language in cache lookups.
-
accessor
= None¶
-
cache_name
¶
-
-
class
cms.core.translations.fields.
NONE
¶ Used for fallback options when they are not provided (
None
can be given as a fallback or undefined value) or to mark that a nullable value is not yet known and needs to be computed (e.g. field default).
-
class
cms.core.translations.fields.
TranslatedRelationIdDescriptor
(field_name, fallback_languages)¶ Bases:
object
A descriptor used for the original ‘_id’ attribute of a translated ForeignKey field.
-
class
cms.core.translations.fields.
TranslationField
(translated_field, language, empty_value, *args, **kwargs)¶ Bases:
object
The translation field functions as a proxy to the original field which is wrapped.
For every field defined in the model’s
TranslationOptions
localized versions of that field are added to the model depending on the languages given insettings.LANGUAGES
.If for example there is a model
News
with a fieldtitle
which is registered for translation and thesettings.LANGUAGES
contains thede
anden
languages, the fieldstitle_de
andtitle_en
will be added to the model class. These fields are realized using this descriptor.The translation field needs to know which language it contains therefore that needs to be specified when the field is created.
-
deconstruct
()¶
-
formfield
(*args, **kwargs)¶ Returns proper formfield, according to empty_values setting (only for
forms.CharField
subclasses).There are 3 different formfields: - CharField that stores all empty values as empty strings; - NullCharField that stores all empty values as None (Null); - NullableField that can store both None and empty string.
By default, if no empty_values was specified in model’s translation options, NullCharField would be used if the original field is nullable, CharField otherwise.
This can be overridden by setting empty_values to ‘’ or None.
Setting ‘both’ will result in NullableField being used. Textual widgets (subclassing
TextInput
orTextarea
) used for nullable fields are enriched with a clear checkbox, allowingNone
values to be preserved rather than saved as empty strings.The
forms.CharField
somewhat surprising behaviour is documented as a “won’t fix”: https://code.djangoproject.com/ticket/9590.
-
save_form_data
(instance, data, check=True)¶
-
-
class
cms.core.translations.fields.
TranslationFieldDescriptor
(field, fallback_languages=None, fallback_value=<class cms.core.translations.fields.NONE at 0x3063120>, fallback_undefined=<class cms.core.translations.fields.NONE at 0x3063120>)¶ Bases:
object
A descriptor used for the original translated field.
-
meaningful_value
(val, undefined)¶ Check if val is considered non-empty.
-
-
cms.core.translations.fields.
create_translation_field
(model, field_name, lang, empty_value)¶ Translation field factory. Returns a
TranslationField
based on a fieldname and a language.The list of supported fields can be extended by defining a tuple of field names in the projects settings.py like this:
MODELTRANSLATION_CUSTOM_FIELDS = ('MyField', 'MyOtherField',)
If the class is neither a subclass of fields in
SUPPORTED_FIELDS
, nor inCUSTOM_FIELDS
anImproperlyConfigured
exception will be raised.
-
cms.core.translations.fields.
field_factory
(baseclass)¶
cms.core.translations.forms module¶
-
class
cms.core.translations.forms.
NullCharField
(max_length=None, min_length=None, placeholder=None, jsvalidate=None, *args, **kwargs)¶ Bases:
django.forms.fields.CharField
CharField subclass that returns
None
whenCharField
would return empty string.-
to_python
(value)¶
-
-
class
cms.core.translations.forms.
NullableField
(required=True, widget=None, label=None, initial=None, help_text=u'', error_messages=None, show_hidden_initial=False, validators=[], localize=False)¶ Bases:
django.forms.fields.Field
Form field mixin that ensures that
None
is not cast to anything (like the empty string withCharField
and its derivatives).-
to_python
(value)¶
-
cms.core.translations.manager module¶
-
class
cms.core.translations.manager.
FallbackValuesListQuerySet
(*args, **kwargs)¶ Bases:
cms.core.translations.manager.FallbackValuesQuerySet
-
iterator
()¶
-
-
class
cms.core.translations.manager.
FallbackValuesQuerySet
(*args, **kwargs)¶ Bases:
django.db.models.query.ValuesQuerySet
,cms.core.translations.manager.MultilingualQuerySet
-
FallbackValuesQuerySet.
iterator
()¶
-
-
class
cms.core.translations.manager.
MultilingualManager
¶ Bases:
cms.core.translations.manager.MultilingualQuerysetManager
-
get_query_set
(*args, **kwargs)¶
-
get_queryset
()¶ This method is repeated because some managers that don’t use super() or alter queryset class may return queryset that is not subclass of MultilingualQuerySet.
-
populate
(*args, **kwargs)¶
-
raw_values
(*args, **kwargs)¶
-
rewrite
(*args, **kwargs)¶
-
-
class
cms.core.translations.manager.
MultilingualQuerySet
(*args, **kwargs)¶ Bases:
django.db.models.query.QuerySet
-
create
(**kwargs)¶ Allows to override population mode with a
populate
method.
-
dates
(field_name, *args, **kwargs)¶
-
defer
(*fields)¶
-
get_or_create
(**kwargs)¶ Allows to override population mode with a
populate
method.
-
only
(*fields)¶
-
order_by
(*field_names)¶ Change translatable field names in an
order_by
argument to translation fields for the current language.
-
populate
(mode='all')¶ Overrides the translation fields population mode for this query set.
-
raw_values
(*fields)¶
-
rewrite
(mode=True)¶
-
update
(**kwargs)¶
-
values
(*fields)¶
-
values_list
(*fields, **kwargs)¶
-
-
class
cms.core.translations.manager.
MultilingualQuerysetManager
¶ Bases:
django.db.models.manager.Manager
This class gets hooked in MRO just before plain Manager, so that every call to get_queryset returns MultilingualQuerySet.
-
get_query_set
()¶
-
get_queryset
()¶
-
-
cms.core.translations.manager.
append_fallback
(model, fields)¶ If translated field is encountered, add also all its fallback fields. Returns tuple: (set_of_new_fields_to_use, set_of_translated_field_names)
-
cms.core.translations.manager.
append_lookup_key
(model, lookup_key)¶ Transform spanned__lookup__key into all possible translation versions, on all levels
-
cms.core.translations.manager.
append_lookup_keys
(model, fields)¶
-
cms.core.translations.manager.
append_translated
(model, fields)¶ If translated field is encountered, add also all its translation fields.
-
cms.core.translations.manager.
get_field_by_colum_name
(model, col)¶
-
cms.core.translations.manager.
get_fields_to_translatable_models
(model)¶
-
cms.core.translations.manager.
get_queryset
(obj)¶
-
cms.core.translations.manager.
get_translatable_fields_for_model
(model)¶
-
cms.core.translations.manager.
multilingual_queryset_factory
(old_cls, instantiate=True)¶
-
cms.core.translations.manager.
rewrite_lookup_key
(model, lookup_key)¶
-
cms.core.translations.manager.
rewrite_order_lookup_key
(model, lookup_key)¶
cms.core.translations.middleware module¶
-
class
cms.core.translations.middleware.
TranslationsMiddleware
¶ Bases:
django.middleware.locale.LocaleMiddleware
This is a very simple middleware that parses a request and decides what translation object to install in the current thread context. This allows pages to be dynamically translated to the language the user desires (if the language is available, of course).
-
process_request
(request)¶
-
process_response
(request, response)¶
-
response_redirect_class
¶ alias of
HttpResponsePermanentRedirect
-
cms.core.translations.models module¶
cms.core.translations.settings module¶
cms.core.translations.translator module¶
-
exception
cms.core.translations.translator.
AlreadyRegistered
¶ Bases:
exceptions.Exception
-
exception
cms.core.translations.translator.
DescendantRegistered
¶ Bases:
exceptions.Exception
-
class
cms.core.translations.translator.
FieldsAggregationMetaClass
¶ Bases:
type
Metaclass to handle custom inheritance of fields between classes.
-
exception
cms.core.translations.translator.
NotRegistered
¶ Bases:
exceptions.Exception
-
class
cms.core.translations.translator.
TranslationOptions
(model)¶ Bases:
object
Translatable fields are declared by registering a model using
TranslationOptions
class with appropriatefields
attribute. Model-specific fallback values and languages can also be given as class attributes.Options instances hold info about translatable fields for a model and its superclasses. The
local_fields
andfields
attributes are mappings from fields to sets of their translation fields;local_fields
contains only those fields that are handled in the model’s database table (those inherited from abstract superclasses, unless there is a concrete superclass in between in the inheritance chain), whilefields
also includes fields inherited from concrete supermodels (giving all translated fields available on a model).related
attribute inform whether this model is related part of some relation with translated model. This model may be not translated itself.related_fields
contains names of reverse lookup fields.-
add_translation_field
(field, translation_field)¶ Add a new translation field to both fields dicts.
-
fields
= ()¶
-
get_field_names
()¶ Return name of all fields that can be used in filtering.
-
required_languages
= ()¶
-
update
(other)¶ Update with options from a superclass.
-
validate
()¶ Perform options validation.
-
-
class
cms.core.translations.translator.
Translator
¶ Bases:
object
A Translator object encapsulates an instance of a translator. Models are registered with the Translator using the register() method.
-
get_options_for_model
(model)¶ Thin wrapper around
_get_options_for_model
to preserve the semantic of throwing exception for models not directly registered.
-
get_registered_models
(abstract=True)¶ Returns a list of all registered models, or just concrete registered models.
-
register
(model_or_iterable, opts_class=None, **options)¶ Registers the given model(s) with the given translation options.
The model(s) should be Model classes, not instances.
Fields declared for translation on a base class are inherited by subclasses. If the model or one of its subclasses is already registered for translation, this will raise an exception.
-
unregister
(model_or_iterable)¶ Unregisters the given model(s).
If a model isn’t registered, this will raise NotRegistered. If one of its subclasses is registered, DescendantRegistered will be raised.
-
-
cms.core.translations.translator.
add_manager
(model)¶ Monkey patches the original model to use MultilingualManager instead of default managers (not only
objects
, but also every manager defined and inherited).Custom managers are merged with MultilingualManager.
-
cms.core.translations.translator.
add_translation_fields
(model, opts)¶ Monkey patches the original model class to provide additional fields for every language.
Adds newly created translation fields to the given translation options.
-
cms.core.translations.translator.
delete_cache_fields
(model)¶
-
cms.core.translations.translator.
delete_mt_init
(sender, instance, **kwargs)¶
-
cms.core.translations.translator.
has_custom_queryset
(manager)¶ Check whether manager (or its parents) has declared some custom get_queryset method.
-
cms.core.translations.translator.
patch_clean_fields
(model)¶ Patch clean_fields method to handle different form types submission.
-
cms.core.translations.translator.
patch_constructor
(model)¶ Monkey patches the original model to rewrite fields names in __init__
-
cms.core.translations.translator.
patch_metaclass
(model)¶ Monkey patches original model metaclass to exclude translated fields on deferred subclasses.
Patch SingleRelatedObjectDescriptor or ReverseSingleRelatedObjectDescriptor to use language-aware caching.
-
cms.core.translations.translator.
populate_translation_fields
(sender, kwargs)¶ When models are created or loaded from fixtures, replicates values provided for translatable fields to some / all empty translation fields, according to the current population mode.
Population is performed only on keys (field names) present in kwargs. Nothing is returned, but passed kwargs dictionary is altered.
With
mode
set to: –all
: fills all translation fields, skipping just those forwhich a translated value is also provided;- –
default
: fills only the default translation (unless it is - additionally provided);
- –
required
: likedefault
, but only if the original field is - non-nullable;
At least the
required
mode should be used when loading untranslated fixtures to keep the database consistent (note that Django management commands are normally forced to run with hardcodeden-us
language active). Thedefault
mode is useful if you need to ensure fallback values are available, andall
if you need to have all translations defined (for example to make lookups / filtering without resorting to query fallbacks).- –
cms.core.translations.utils module¶
-
cms.core.translations.utils.
auto_populate
(*args, **kwds)¶ Overrides translation fields population mode (population mode decides which unprovided translations will be filled during model construction / loading).
Example:
- with auto_populate(‘all’):
- s = Slugged.objects.create(title=’foo’)
s.title_en == ‘foo’ // True s.title_de == ‘foo’ // True
This method may be used to ensure consistency loading untranslated fixtures, with non-default language active:
- with auto_populate(‘required’):
- call_command(‘loaddata’, ‘fixture.json’)
-
cms.core.translations.utils.
build_css_class
(localized_fieldname, prefix='')¶ Returns a css class based on
localized_fieldname
which is easily splitable and capable of regionalized language codes.Takes an optional
prefix
which is prepended to the returned string.
-
cms.core.translations.utils.
build_localized_fieldname
(field_name, lang)¶
-
cms.core.translations.utils.
build_localized_verbose_name
(*args, **kw)¶
-
cms.core.translations.utils.
fallbacks
(*args, **kwds)¶ Temporarily switch all language fallbacks on or off.
Example:
- with fallbacks(False):
- lang_has_slug = bool(self.slug)
May be used to enable fallbacks just when they’re needed saving on some processing or check if there is a value for the current language (not knowing the language)
-
cms.core.translations.utils.
get_translation_fields
(field)¶ Returns a list of localized fieldnames for a given field.
-
cms.core.translations.utils.
parse_field
(setting, field_name, default)¶ Extract result from single-value or dict-type setting like fallback_values.
-
cms.core.translations.utils.
resolution_order
(lang, override=None)¶ Return order of languages which should be checked for parameter language. First is always the parameter language, later are fallback languages. Override parameter has priority over FALLBACK_LANGUAGES.
-
cms.core.translations.utils.
unique
(seq)¶ >>> list(unique([1, 2, 3, 2, 2, 4, 1])) [1, 2, 3, 4]
cms.core.translations.views module¶
-
class
cms.core.translations.views.
TranslateSuggestView
(**kwargs)¶ Bases:
django.views.generic.base.View
-
get
(request)¶
-
cms.core.translations.widgets module¶
-
class
cms.core.translations.widgets.
ClearableWidgetWrapper
(widget, empty_value=None)¶ Bases:
django.forms.widgets.Widget
Wraps another widget adding a clear checkbox, making it possible to reset the field to some empty value even if the original input doesn’t have means to.
Useful for
TextInput
andTextarea
based widgets used in combination with nullable text fields.Use it in
Field.formfield
orModelAdmin.formfield_for_dbfield
:field.widget = ClearableWidgetWrapper(field.widget)None
is assumed to be a proper choice for the empty value, but you may pass another one to the constructor.-
ClearableWidgetWrapper.
clear_checkbox_id
(name)¶ Given the name of the clear checkbox input, returns the HTML id for it.
-
ClearableWidgetWrapper.
clear_checkbox_label
= <django.utils.functional.__proxy__ object at 0x305da50>¶
-
ClearableWidgetWrapper.
clear_checkbox_name
(name)¶ Given the name of the input, returns the name of the clear checkbox.
-
ClearableWidgetWrapper.
media
¶ Combines media of both components and adds a small script that unchecks the clear box, when a value in any wrapped input is modified.
-
ClearableWidgetWrapper.
render
(name, value, attrs=None)¶ Appends a checkbox for clearing the value (that is, setting the field with the
empty_value
).
-
ClearableWidgetWrapper.
template
= u'<span class="clearable-input">{0} <span>{2}</span> {3}</span>'¶
-
ClearableWidgetWrapper.
value_from_datadict
(data, files, name)¶ If the clear checkbox is checked returns the configured empty value, completely ignoring the original input.
-