django-modeltranslation
django-modeltranslation copied to clipboard
Inheritance issue
I am having problems with simple inheritance.
Here is my models.py:
class BaseSegment(models.Model):
name = models.CharField(max_length=256, verbose_name=_("Name"), unique=True)
class Segment(BaseSegment):
label = models.CharField(max_length=256, verbose_name=_("Label"), default='')
description = models.TextField(verbose_name=_("Description"), default='')
And my translation.py:
from modeltranslation.translator import translator, TranslationOptions
from models import BaseSegment, Segment
class BaseSegmentOptions(TranslationOptions):
fields = ('name',)
class SegmentOptions(BaseSegmentOptions):
fields = ('label', 'description')
translator.register(BaseSegment, BaseSegmentOptions)
translator.register(Segment, SegmentOptions)
This does not work, Django (1.8.0) complains when trying to makemigrations:
SystemCheckError: System check identified some issues:
ERRORS:
base.Segment.name_de: (models.E006) The field 'name_de' clashes with the field 'name_de' from model 'base.basesegment'.
base.Segment.name_en: (models.E006) The field 'name_en' clashes with the field 'name_en' from model 'base.basesegment'.
base.Segment.name_fr: (models.E006) The field 'name_fr' clashes with the field 'name_fr' from model 'base.basesegment'.
I have tried just registering the SegmentModel, practically without this line
translator.register(BaseSegment, BaseSegmentOptions)
But then, modeltranslation complains:
modeltranslation.translator.NotRegistered: The model "BaseSegment" is not registered for translation
I have tried skipping BaseSegment alltogether, adding the 'name' field to SegmentOptions, but then the 'name' field seems completely empty (although it is already pre-populated in the 'name' field in BaseSegment).
What am I doing wrong?
Django v1.8.6 - same behaviour.
I'm having the same issue with normal inheritance, also after upgrading.
Fixed by loading modeltranslation
before django.contrib.admin
in INSTALLED_APPS
.
Interesting, it will be very useful put that in the documentation.
Gosh, it's there, just read it carefully: http://django-modeltranslation.readthedocs.org/en/latest/installation.html#required-settings
@romansemko
You need to change SegmentOptions
to NOT inherit from BaseSegmentOptions
.
That's because fields are inherited this way: http://django-modeltranslation.readthedocs.org/en/latest/registration.html#translationoptions-fields-inheritance
And SegmentOptions.fields == ('name', 'label', 'description')
. But name
is the field not on Segment
, but on BaseSegment
only.
Just inherit SegmentOptions
from TranslationOptions
.
No other change in your code is required.
.
It is all a bit un-intuitive at first but you'll figure it out when you go through the codebase.
This scenario could have been handled more elegantly though.