Django Modeltranslation enables translation of Django model fields. Unfold enhances this with a custom TabbedTranslationAdmin implementation that provides tabbed navigation for different languages, making it easy to manage translations directly in the admin interface.
Modeltranslation works by creating additional database fields for each translated field and language, keeping all translations in the same table.
@register(Article)class ArticleTranslationOptions(TranslationOptions): fields = ("title", "content") required_languages = ("en", "es") # English and Spanish required # Other languages are optional
@register(Article)class ArticleTranslationOptions(TranslationOptions): fields = ("title", "content", "excerpt") # Title required in all languages required_languages = { "title": ("en", "es", "fr"), "content": ("en",), # Content only required in English }
from django.utils.translation import activatefrom myapp.models import Article# Create article with English contentarticle = Article.objects.create( title_en="Hello World", content_en="This is the English content", title_es="Hola Mundo", content_es="Este es el contenido en español",)# Or use translation.activateactivate("en")article.title = "Hello World"article.content = "English content"activate("es")article.title = "Hola Mundo"article.content = "Contenido en español"article.save()
from django.utils.translation import activate# Query in current languageactivate("es")articles = Article.objects.filter(title__icontains="mundo")# Query specific language fieldarticles = Article.objects.filter(title_es__icontains="mundo")# Get all articles with Spanish translationarticles = Article.objects.exclude(title_es__isnull=True)
# In a data migrationdef copy_to_default_language(apps, schema_editor): Article = apps.get_model("myapp", "Article") for article in Article.objects.all(): article.title_en = article.title article.content_en = article.content article.save()
# Only load current language fieldsArticle.objects.all().values("title", "content")# Explicitly load specific languagesArticle.objects.all().values("title_en", "title_es")
class Article(models.Model): title = models.CharField(max_length=200) class Meta: indexes = [ models.Index(fields=["title_en"]), models.Index(fields=["title_es"]), ]