本文整理汇总了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函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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
示例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'
示例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
示例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
示例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)
示例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
示例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')
示例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
示例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
示例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
}
示例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
}
示例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)
示例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
示例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