In this article, we are going to learn how to create a translation for any instance. Sometimes, you may need to save data like ID, names, quotes, lines, etc. You may have to render that data in different languages; for that, you need to do a lot of database stuff, but today I will show you how to get the same result in just a few lines of setup.
Create a Django project and an app. Setup urls and do some basic stuff like adding app in INSTALLED_APPS.
Create a model. Here, we don't have much to do with views.py, urls.py or any html file. We only have work with settings.py, admin.py, models.py and admin urlpoint.
Install the django-klingon package −
pip install django-klingon
In settings.py, add this −
INSTALLED_APPS += ['klingon'] KLINGON_DEFAULT_LANGUAGE = 'en'
Here, we do the basic setting of adding klingon as an app in the project and we define English as its default language.
Create a model like this −
from django.db import models from klingon.models import Translatable # add translatable class TeacherData(models.Model,Translatable): name=models.CharField(max_length=100) # first3 simple fields ClassTeacherOF=models.CharField(max_length=100) Salary=models.CharField(max_length=100) a_simple_word=models.CharField(max_length=100) # define field that will be translated translatable_fields = ('a_simple_word')
Here, we simply created a model. Point to be noted here is that we created a translatable field which will tell which field is needed to be translated and it is reference to our translated object in different table.
In admins.py, add the following code −
from django.contrib import admin from .models import TeacherData from klingon.admin import TranslationInline, create_translations class TeacherAdmin(admin.ModelAdmin): inlines = [TranslationInline] actions = [create_translations] admin.site.register(TeacherData,TeacherAdmin)
Here, we simply added our model to admin url and add kligon translation reference in admin.
Now, all is done. Let's check the output.
Run Python shell and do this to add a translation for the newly created object −
In : from formhandlingapp.models import * In : data=TeachertData.objects.create(name="ama4",ClassTeacherOF=" 10",Salary="33322",a_simple_word="how are you") In : data.set_translation('jp', 'a_simple_word','お元気ですか')
Now, you can see a translation object created, obviously you can add this through views.py