本文整理汇总了Python中modeltranslation.translator.translator.get_options_for_model函数的典型用法代码示例。如果您正苦于以下问题:Python get_options_for_model函数的具体用法?Python get_options_for_model怎么用?Python get_options_for_model使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_options_for_model函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: handle
def handle(self, *args, **options):
file_class_map = {
'auteur': Artist, # no parent
'collect': CollectMethod,
'stade-creation': CreationState,
'denomination': Denomination,
'domain': Domain,
'inscriptions': InscriptionType,
'lieu': GeographicalLocation,
'juridique': LegalState,
'techniques': MaterialTechnique,
'datation': Period,
'sources-representation': RepresentationSource,
'sujet': RepresentationSubject,
'ecole': School,
'epoque': StyleEra,
'utilisations': UsageDestination,
}
model_class = None
for k, v in file_class_map.items():
if k in args[0]:
model_class = v
break
if not model_class:
print "What to do with" + args[0]
return
r = csv.reader(open(args[0], 'U'), delimiter=',')
current = []
for row in r:
i = 0
for node in row:
name = node.strip('", ').decode('utf-8')
if name:
if '=' in name:
names = [x.strip() for x in name.split('=')]
name = '%s (%s)' % (names[0].strip(), ', '.join(names[1:]))
o = {}
try:
translator.get_options_for_model(model_class)
o['name_fr'] = name
except:
o['name'] = name
if i > 0:
o['parent'] = current[i-1]
model, created = model_class.objects.get_or_create(**o)
if len(current) < i + 1:
current.append(model)
else:
current[i] = model
i += 1
开发者ID:jpic,项目名称:django-art,代码行数:59,代码来源:art_import_tree_csv.py
示例2: populate_exclude
def populate_exclude(exclude, model):
"""handles exclude"""
trans_opts = translator.get_options_for_model(model)
for fn in exclude[:]:
for tf in trans_opts.fields.get(fn, set()):
exclude.append(tf.name)
return exclude
开发者ID:emacsway,项目名称:django-modeltranslation-ext,代码行数:7,代码来源:utils.py
示例3: handle_noargs
def handle_noargs(self, **options):
"""
Command execution.
"""
self.cursor = connection.cursor()
self.introspection = connection.introspection
found_missing_fields = False
models = translator.get_registered_models(abstract=False)
for model in models:
db_table = model._meta.db_table
model_full_name = '%s.%s' % (model._meta.app_label, model._meta.module_name)
opts = translator.get_options_for_model(model)
for field_name in opts.local_fields.iterkeys():
missing_langs = list(self.get_missing_languages(field_name, db_table))
if missing_langs:
found_missing_fields = True
print_missing_langs(missing_langs, field_name, model_full_name)
sql_sentences = self.get_sync_sql(field_name, missing_langs, model)
execute_sql = ask_for_confirmation(sql_sentences, model_full_name)
if execute_sql:
print 'Executing SQL...',
for sentence in sql_sentences:
self.cursor.execute(sentence)
print 'Done'
else:
print 'SQL not executed'
transaction.commit_unless_managed()
if not found_missing_fields:
print 'No new translatable fields detected'
开发者ID:PlatonovIvan,项目名称:secsem-site,代码行数:32,代码来源:sync_translation_fields.py
示例4: formfield_exclude_translations
def formfield_exclude_translations(db_field, **kwargs):
"""Filter form and keep only non-localized fields"""
if hasattr(db_field, 'translated_field'):
return None
if 'field' in kwargs:
field = kwargs['field']
else:
field = db_field.formfield(**kwargs)
if not field:
return field
trans_opts = translator.get_options_for_model(db_field.model)
if db_field.name in trans_opts.fields:
field.widget.attrs['class'] = '{0} {1}'.format(
getattr(field.widget.attrs, 'class', ''),
'language-depended'
)
field.help_text = string_concat(
field.help_text,
_(' '),
_('This field dependent on current language.')
)
return field
开发者ID:emacsway,项目名称:django-modeltranslation-ext,代码行数:25,代码来源:utils.py
示例5: get_translatable_fields_for_model
def get_translatable_fields_for_model(model):
from modeltranslation.translator import NotRegistered, translator
try:
return translator.get_options_for_model(model).get_field_names()
except NotRegistered:
return None
开发者ID:qdqmedia,项目名称:django-modeltranslation,代码行数:7,代码来源:manager.py
示例6: patch_translation_field
def patch_translation_field(self, db_field, field, **kwargs):
trans_opts = translator.get_options_for_model(self.model)
# Hide the original field by making it non-editable.
if db_field.name in trans_opts.fields:
db_field.editable = False
# For every localized field copy the widget from the original field
# and add a css class to identify a modeltranslation widget.
if db_field.name in trans_opts.localized_fieldnames_rev:
orig_fieldname = trans_opts.localized_fieldnames_rev[db_field.name]
orig_formfield = self.formfield_for_dbfield(\
self.model._meta.get_field(orig_fieldname),
**kwargs)
field.widget = copy(orig_formfield.widget)
css_classes = field.widget.attrs.get('class', '').split(' ')
css_classes.append('modeltranslation')
if db_field.language == DEFAULT_LANGUAGE:
# Add another css class to identify a default modeltranslation
# widget.
css_classes.append('modeltranslation-default')
if orig_formfield.required:
# In case the original form field was required, make the default
# translation field required instead.
orig_formfield.required = False
orig_formfield.blank = True
field.required = True
field.blank = False
field.widget.attrs['class'] = ' '.join(css_classes)
开发者ID:kellycreativetech,项目名称:django-modeltranslation,代码行数:31,代码来源:admin.py
示例7: __init__
def __init__(self, *args, **kwargs):
super(CurLocaleModelForm, self).__init__(*args, **kwargs)
# trans_fields will contain dict from original field name to localized bound
# formfield for current locale.
# This is useful in templates to render localized field by original name without
# locale suffix. For example to render localized name field in template you can write:
# {{form.trans_fields.name}}
# if current locale is 'en' it is equivalent to:
# {{form.name_en}}
self.trans_fields = {}
model_trans_fields = translator.get_options_for_model(self._meta.model).fields
lang = get_language()
for f in self._meta.model._meta.fields:
if f.name not in self.fields:
continue
if f.name in model_trans_fields:
del self.fields[f.name] # Delete original unlocalized fields
elif isinstance(f, TranslationField):
if not f.name.endswith('_' + lang):
# Delete localized field for other language
del self.fields[f.name]
else:
# Set trans_fields mapping from original field name to this field
self.trans_fields[f.translated_field.name] = self[f.name]
if not f.translated_field.blank:
# Original modelfield has blank=False attribute, we should set "required" flag on
# localized formfield for current language.
self.fields[f.name].required = True
开发者ID:TransparenCEE,项目名称:exmo2010,代码行数:31,代码来源:__init__.py
示例8: handle_noargs
def handle_noargs(self, **options):
"""
Command execution.
"""
self.interactive = options['interactive']
models = translator.get_registered_models(abstract=False)
found_bad_fields = False
for model in models:
db_table = model._meta.db_table
model_full_name = '%s.%s' % (model._meta.app_label, model._meta.module_name)
opts = translator.get_options_for_model(model)
for field_name in opts.local_fields.keys():
bad_lang_field_names = self.get_bad_lang_field_names(field_name, db_table)
if bad_lang_field_names:
found_bad_fields = True
print_bad_langs(bad_lang_field_names, field_name, model_full_name)
sql_sentences = self.get_alter_sql(bad_lang_field_names, model)
execute_sql = ask_for_confirmation(
sql_sentences, model_full_name, self.interactive)
if execute_sql:
print('Executing SQL...')
for sentence in sql_sentences:
self.cursor.execute(sentence)
print('Done')
else:
print('SQL not executed')
if not found_bad_fields:
print('No new translatable fields detected')
开发者ID:NyakudyaA,项目名称:core,代码行数:30,代码来源:remove_unused_translation_fields.py
示例9: _patch_simple_panel
def _patch_simple_panel(self, model, original_panel):
panel_class = original_panel.__class__
translated_panels = []
translation_registered_fields = translator.get_options_for_model(model).fields
# If the panel field is not registered for translation
# the original one is returned
if original_panel.field_name not in translation_registered_fields:
return [original_panel]
for language in mt_settings.AVAILABLE_LANGUAGES:
original_field = model._meta.get_field(original_panel.field_name)
localized_field_name = build_localized_fieldname(original_panel.field_name, language)
# if the original field is required and the current language is the default one
# this field's blank property is set to False
if not original_field.blank and language == mt_settings.DEFAULT_LANGUAGE:
localized_field = model._meta.get_field(localized_field_name)
localized_field.blank = False
localized_panel = panel_class(localized_field_name)
# Pass the original panel extra attributes to the localized
if hasattr(original_panel, 'classname'):
localized_panel.classname = original_panel.classname
if hasattr(original_panel, 'widget'):
localized_panel.widget = original_panel.widget
translated_panels.append(localized_panel)
return translated_panels
开发者ID:sinnwerkstatt,项目名称:wagtail-modeltranslation,代码行数:31,代码来源:patch_wagtailadmin.py
示例10: formfield_exclude_irrelevant
def formfield_exclude_irrelevant(db_field, **kwargs):
""" only localized fields """
from modeltranslation.translator import translator
from modeltranslation.utils import get_language
trans_opts = translator.get_options_for_model(db_field.model)
if db_field.name in trans_opts.fields:
return None
if 'field' in kwargs:
field = kwargs['field']
else:
field = db_field.formfield(**kwargs)
if hasattr(db_field, 'translated_field'):
if db_field.name.endswith('_{0}'.format(get_language())):
field.required = True
field.widget.attrs['class'] = '{0} {1}'.format(
getattr(field.widget.attrs, 'class', ''),
'language-depended'
)
field.help_text = string_concat(
field.help_text,
_(' '),
_('This field dependent on current language.')
)
else:
return None
return field
开发者ID:liminspace,项目名称:dj-utils,代码行数:26,代码来源:modeltranslation.py
示例11: __init__
def __init__(self, progress_cb=None):
self.warnings = {}
self.line = 0
self.nb_success = 0
self.nb_created = 0
self.nb_updated = 0
self.nb_unmodified = 0
self.progress_cb = progress_cb
try:
mto = translator.get_options_for_model(self.model)
except NotRegistered:
self.translated_fields = []
else:
self.translated_fields = mto.fields.keys()
if self.fields is None:
self.fields = {
f.name: force_text(f.verbose_name)
for f in self.model._meta.fields
if not isinstance(f, TranslationField)
}
self.m2m_fields = {
f.name: force_text(f.verbose_name)
for f in self.model._meta.many_to_many
}
开发者ID:Kristof-DM,项目名称:Geotrek,代码行数:26,代码来源:parsers.py
示例12: __init__
def __init__(self, progress_cb=None, user=None, encoding='utf8'):
self.warnings = {}
self.line = 0
self.nb_success = 0
self.nb_created = 0
self.nb_updated = 0
self.nb_unmodified = 0
self.progress_cb = progress_cb
self.user = user
self.structure = user and user.profile.structure or default_structure()
self.encoding = encoding
try:
mto = translator.get_options_for_model(self.model)
except NotRegistered:
self.translated_fields = []
else:
self.translated_fields = mto.fields.keys()
if self.fields is None:
self.fields = {
f.name: force_text(f.verbose_name)
for f in self.model._meta.fields
if not isinstance(f, TranslationField)
}
self.m2m_fields = {
f.name: force_text(f.verbose_name)
for f in self.model._meta.many_to_many
}
开发者ID:makinacorpus,项目名称:Geotrek,代码行数:29,代码来源:parsers.py
示例13: replace_orig_fields
def replace_orig_fields(self):
self.orig_fields = self.fields.keys()
# Expand i18n fields
try:
# Obtain model translation options
mto = translator.get_options_for_model(self._meta.model)
except NotRegistered:
# No translation field on this model, nothing to do
return
# For each translated model field
for modelfield in mto.fields:
if modelfield not in self.fields:
continue
# Remove form native field (e.g. `name`)
native = self.fields.pop(modelfield)
# Add translated fields (e.g. `name_fr`, `name_en`...)
for l in app_settings['TRANSLATED_LANGUAGES']:
lang = l[0]
name = '%s_%s' % (modelfield, lang)
# Add to form.fields{}
translated = copy.deepcopy(native)
translated.required = native.required and (lang == app_settings['LANGUAGE_CODE'])
translated.label = u"%s [%s]" % (translated.label, lang)
self.fields[name] = translated
# Keep track of replacements
self._translated.setdefault(modelfield, []).append(name)
开发者ID:makinacorpus,项目名称:django-mapentity,代码行数:26,代码来源:forms.py
示例14: localize_fieldname
def localize_fieldname(self, name, model=None, lang=None):
"""Localizes translatable field name"""
model = model or self.model
trans_opts = translator.get_options_for_model(model)
if name in trans_opts.fields:
return localize_fieldname(name, lang)
return name
开发者ID:emacsway,项目名称:django-modeltranslation-ext,代码行数:7,代码来源:managers.py
示例15: __init__
def __init__(self, *args, **kwargs):
super(TranslationAdmin, self).__init__(*args, **kwargs)
trans_opts = translator.get_options_for_model(self.model)
# Replace original field with translation field for each language
if self.fields:
fields_new = list(self.fields)
for field in self.fields:
if field in trans_opts.fields:
index = fields_new.index(field)
translation_fields = get_translation_fields(field)
fields_new[index : index + 1] = translation_fields
self.fields = fields_new
if self.fieldsets:
fieldsets_new = list(self.fieldsets)
for (name, dct) in self.fieldsets:
if "fields" in dct:
tfields_new = []
for field in list(dct["fields"]):
if isinstance(field, tuple):
tfields = []
for f in field:
if f in trans_opts.fields:
tfields.extend(get_translation_fields(f))
else:
tfields.extend((f,))
# FIXME: Flatten nested tuples as they will break in the
# current tabs implementation. Normally we want:
# tfields_new.append(tuple(tfields))
tfields_new.append(tuple(tfields))
else:
if field in trans_opts.fields:
tfields_new.extend(get_translation_fields(field))
else:
tfields_new.extend((field,))
dct["fields"] = tuple(tfields_new)
self.fieldsets = fieldsets_new
if self.list_editable:
editable_new = list(self.list_editable)
display_new = list(self.list_display)
for field in self.list_editable:
if field in trans_opts.fields:
index = editable_new.index(field)
display_index = display_new.index(field)
translation_fields = get_translation_fields(field)
editable_new[index : index + 1] = translation_fields
display_new[display_index : display_index + 1] = translation_fields
self.list_editable = editable_new
self.list_display = display_new
if self.prepopulated_fields:
prepopulated_fields_new = dict(self.prepopulated_fields)
for (k, v) in self.prepopulated_fields.items():
if v[0] in trans_opts.fields:
translation_fields = get_translation_fields(v[0])
prepopulated_fields_new[k] = tuple([translation_fields[0]])
self.prepopulated_fields = prepopulated_fields_new
开发者ID:beholderrk,项目名称:django-modeltranslation,代码行数:59,代码来源:admin.py
示例16: _patch_page_models
def _patch_page_models(self, model):
# PANEL PATCHING
# Check if the model has a custom edit handler
if hasattr(model, 'edit_handler'):
tabs = model.edit_handler.children
for tab in tabs:
tab.children = self._patch_panels(tab.children)
else:
# If the page doesn't have an edit_handler we patch the panels that
# wagtail uses by default
if hasattr(model, 'content_panels'):
model.content_panels = self._patch_panels(model.content_panels)
if hasattr(model, 'promote_panels'):
model.promote_panels = self._patch_panels(model.promote_panels)
if hasattr(model, 'settings_panels'):
model.settings_panels = self._patch_panels(model.settings_panels)
# Clear the edit handler cached value, if it exists, so wagtail reconstructs
# the edit_handler based on the patched panels
model.get_edit_handler.cache_clear()
# SEARCH FIELDS PATCHING
translation_registered_fields = translator.get_options_for_model(model).fields
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 translation_registered_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 language in mt_settings.AVAILABLE_LANGUAGES:
translated_field = copy.deepcopy(field)
translated_field.field_name = build_localized_fieldname(field.field_name, language)
model.search_fields = list(model.search_fields) + [translated_field]
# OVERRIDE FIELDS
model_fields = model._meta.get_fields()
for field in model_fields:
if isinstance(field, StreamField) and field.name in translation_registered_fields:
descriptor = getattr(model, field.name)
_patch_stream_field_meaningful_value(descriptor)
# OVERRIDE PAGE METHODS
if TRANSLATE_SLUGS:
model.set_url_path = _new_set_url_path
model.route = _new_route
model._update_descendant_url_paths = _new_update_descendant_url_paths
if not hasattr(model, '_get_site_root_paths'):
model.get_url_parts = _new_get_url_parts # Wagtail<1.11
model._get_site_root_paths = _new_get_site_root_paths
_patch_clean(model)
if not model.save.__name__.startswith('localized'):
setattr(model, 'save', LocalizedSaveDescriptor(model.save))
开发者ID:infoportugal,项目名称:wagtail-modeltranslation,代码行数:58,代码来源:patch_wagtailadmin.py
示例17: get_fields_to_translatable_models
def get_fields_to_translatable_models(model):
from modeltranslation.translator import translator
results = []
for field_name in translator.get_options_for_model(model).fields.keys():
field_object, modelclass, direct, m2m = model._meta.get_field_by_name(field_name)
if direct and isinstance(field_object, RelatedField):
if get_translatable_fields_for_model(field_object.related.parent_model) is not None:
results.append((field_name, field_object.related.parent_model))
return results
开发者ID:ljarufe,项目名称:quimerahg,代码行数:9,代码来源:manager.py
示例18: _append_translated
def _append_translated(self, fields):
"If translated field is encountered, add also all its translation fields."
fields = set(fields)
from modeltranslation.translator import translator
opts = translator.get_options_for_model(self.model)
for key, translated in opts.fields.items():
if key in fields:
fields = fields.union(f.name for f in translated)
return fields
开发者ID:trannguyenminhluan,项目名称:django-modeltranslation,代码行数:9,代码来源:manager.py
示例19: get_models
def get_models(self, app):
r = []
for mdname in dir(app.models):
if mdname[0] == '_': continue
md = getattr(app.models, mdname)
try:
opts = translator.get_options_for_model(md)
r.append((md, opts))
except NotRegistered:
continue
return r
开发者ID:prmtl,项目名称:wolnelektury,代码行数:11,代码来源:translation2po.py
示例20: save_model
def save_model(self, request, obj, form, change):
# Rule is: 3. Assigning a value to a translation field of the default language also
# updates the original field.
# Ensure that an empty default language field value clears the default field.
# See issue 47 for details.
trans_opts = translator.get_options_for_model(self.model)
for k, v in trans_opts.localized_fieldnames.items():
if getattr(obj, k):
default_lang_fieldname = build_localized_fieldname(k, DEFAULT_LANGUAGE)
if not getattr(obj, default_lang_fieldname):
# TODO: Handle null values
setattr(obj, k, "")
super(TranslationAdmin, self).save_model(request, obj, form, change)
开发者ID:GunioRobot,项目名称:django-modeltranslation,代码行数:13,代码来源:admin.py
注:本文中的modeltranslation.translator.translator.get_options_for_model函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论