Reputation: 5202
I'm modeling a service catalog where I group services in different categories. Each category is a model with a description among other fields that are not relevant here.
class Category(models.Model):
description = models.TextField()
...
The idea is that additional service categories (or even sub categories) are added as the platform grows. I need to have the description in several languages.
I've considered different approaches to do so, and I need to decide which one is cleaner.
First approach. Model descriptions as db models with the description and a language so I cal filter using the lang code and edit them on the admin
class CategoryDescription(models.Model):
description = models.TextField()
lang = models.CharField(max_length=2)
describes = models.ForeingKey(Category)
class Category(models.Model):
...
Second approach. Remove the description field and use the title of the category as contextual marker. Something like
class Category(models.Model):
one_word_name = models.CharField(max_length=20)
...
And then in the templates.
{% trans "category_description" context category.one_word_name %}
However, my concern here is, Is there an automatic way to generate the ids to be marked as translation? How should I do it?
Upvotes: 1
Views: 3198
Reputation: 10563
To translate your model there is a very useful package I recommend you to check:
With this package you can mark your models for translation, you should follow the tutorial is pretty easy
Anyway the most important steps are:
pip install django-modeltranslation
modeltranslation
to your INSTALLED_APPS
in your settings.py
USE_I18N = True
in settings.py.TranslationOptions
for every model you want to translate.python manage.py syncdb
LANGUAGES in your settings.py:
LANGUAGES = (
('de', gettext('German')),
('en', gettext('English')),
)
translation.py
example:
# -*- coding: utf-8 -*-
# Model Translation
from modeltranslation.translator import translator, TranslationOptions
from models import *
class MyModelTranslationOptions(TranslationOptions):
fields = ('name', 'description') # Select here the fields you want to translate
translator.register(MyModel, MyModelTranslationOptions)
# You can add as many models as you want to translate here
After you define everything and sync the database, the models you choose to translate will have their fields translated.
If you have a field called description
and you mark it as translations, if you're using English and German, django model translation will create the fields description_en
and description_de
where you can add the translations.
Upvotes: 2