问题
I'm trying to use django-modeltranslation
in my project.
For now, just for Tag
model with one field - name
.
I've created and registered TranslationOptions
, then makemigrations
and migrate
.
Now I can't access the original name
text. It seems to be replaced with '' (empty string) but it isn't:
In [6]: Tag.objects.first()
Out[6]: <Tag: >
In [7]: Tag.objects.first().name
Out[7]: u''
In [8]: Tag.objects.first().__dict__
Out[8]:
{'_state': <django.db.models.base.ModelState at 0x7fc96ad41710>,
'id': 1,
'name': u'Sport',
'name_cs': None,
'name_de': None,
'name_en': None,
'name_es': None,
'name_fr': None,
'name_ru': None,
'name_sk': None}
In [9]: Tag.objects.first().name
Out[9]: u''
Do you know how to access the field/s?
EDIT
models.py
class Tag(models.Model):
name = models.CharField(max_length=50,verbose_name=u'Tag',unique=True)
def __unicode__(self):
return self.name
translation.py
from modeltranslation.translator import register, TranslationOptions
from tags.models import Tag
@register(Tag)
class TagsTranslationOptions(TranslationOptions):
fields = ('name',)
settings.py
USE_I18N = True
USE_L10N = False
gettext = lambda x: x
LANGUAGE_CODE = 'en'
LANGUAGES = [
('en', gettext('EN')),
('fr', gettext('FR')),
('es', gettext('ES')),
('de', gettext('DE')),
('ru', gettext('RU')),
('sk', gettext('SK')),
('cs', gettext('CZ')), ]
The same problem is in Admin
:
Detail:
回答1:
According to documentation:
Reading the value from the original field returns the value translated to the current language.
This means that tag.name
doesn't return tag.__dict__['name']
, but rather tag.__dict__['name_en']
(assuming English is an active language).
It looks like you have added modeltranslation to an existing project and you have existing data. In order to get modeltranslation to work properly, you need to run update_translation_fields
, a management command supplied by the app (documentation link). It will copy the data from original field to default translated field (from title
to title_en
).
来源:https://stackoverflow.com/questions/48440899/django-modeltranslation-cant-get-and-see-original-fields