I wanted data in my Django database to be translated to one more language in some cases, and to achieve that I decided to use the django-modeltranslation library. The setup went ok, but the translation fields were never actually added to the models.
I followed the installation steps and created a translation.py file with the following content:
from modeltranslation.translator import translator, TranslationOptions
from .models import *
class WorkTranslationOptions(TranslationOptions):
fields = ('title', 'text') # Select here the fields you want to translate
class CategoryTranslationOptions(TranslationOptions):
fields = ('name',)
translator.register(Work, WorkTranslationOptions)
translator.register(Category, CategoryTranslationOptions)
My models.py file looks like this:
from django.db import models
from django.utils import timezone
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=20, unique = True)
def __str__(self):
return f"{self.name}"
class Work(models.Model):
category = models.ForeignKey(Category, on_delete=models.PROTECT)
app_name = models.CharField(blank=True, null=True, max_length=50)
title = models.CharField(max_length=50, blank=False)
date = models.DateField(blank=False, null=False, default=timezone.now)
icon = models.ImageField(upload_to='works/', blank=False, null=False)
text = models.TextField(blank=False)
url = models.CharField(blank=True, null=True, max_length=50)
def __str__(self):
return f"{self.title}"
Running the python manage.py makemigrations command went fine and returned no exceptions, as well as the migrate command: screenshot But for some reason none of those fields were actually added to the models: I can't see them in the admin panel. How do I fix this?
You should see the fields in the database now. To see them in the Admin as well, inherit from the
TranslationAdmin
when registering your model in the admin.https://django-modeltranslation.readthedocs.io/en/latest/admin.html