我正在尝试翻译模型类上已经存在的字段。我在第一步卡住了,这是子类化Category
中的TranslatableModel
类,并添加TranslatedFields
包装器来翻译选定的模型字段。我正在遵循一本名为"Django by Example"的书以及Django -parler关于如何做到这一点的说明,但是我得到了以下错误:
File ..../env/lib/python3.5/site-packages/parler/models.py", line 965, in contribute_translations
raise TypeError("The model '{0}' already has a field named '{1}'".format(shared_model.__name__, name))
TypeError: The model 'Category' already has a field named 'name'
在应用django-parler之前:
# models.py
class Category(models.Model):
name = models.CharField(max_length=200,
db_index=True)
slug = models.SlugField(max_length=200,
unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_list_by_category',
args=[self.slug])
应用django-parler后:
# models.py
class Category(TranslatableModel):
name = models.CharField(max_length=200,
db_index=True)
slug = models.SlugField(max_length=200,
unique=True)
translations = TranslatedFields(
name = models.CharField(max_length=200,
db_index=True),
slug = models.SlugField(max_length=200,
unique=True),
)
class Meta:
# ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_list_by_category',
args=[self.slug])
好的,从你的代码判断,你正试图遵循"Django by Example" by Antonio Mele....我也有同样的问题。对我来说,修复是在原始模型中使用下划线前缀所有字段,所以……
name = models.CharField(max_length=200,db_index=True)…就变成了_name = models.CharField(max_length=200,db_index=True)
还有一点研究表明,从Django 1.9开始,有一个import重命名为..reveresinglerelatedobjectdescriptor as perhttps://github.com/django-json-api/django-rest-framework-json-api/issues/176
我改变了导入和另一个条件语句引用(第782行)从'ReverseSingleRelatedObjectDescriptor'到'ForwardManyToOneDescriptor'在以下文件"/Django/local/lib/python2.7/site-packages/parler/models.py"..但我不确定最后一步是否真的有必要,我认为重命名就足够了??祝你好运.....
尽管这个问题很老,我还是想贡献一下。添加django-parler后,你的代码片段应该像这样:
<标题> class Category(TranslatableModel):
translations = TranslatedFields(
name = models.CharField(max_length=200,
db_index=True),
slug = models.SlugField(max_length=200,
unique=True),)
class Meta:
# ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_list_by_category',
args=[self.slug])
标题>