I’m new to django, I need to create a translation using the admin panel of janogo to translate this record and save it in the same model. To translate the text I use Yandex api models.py as follows:

from django.db import models from ckeditor.fields import RichTextField import requests class Translations(models.Model): text_origin = RichTextField() lang_text_origin = models.CharField(max_length=10) text_translation = RichTextField() lang_text_translation = models.CharField(max_length=10) 

Now I need to come up with a logic, so that when filling in the text_origin field and saving the record in the text_translation field, a translation is written. The fields lang_text_origin and lang_text_translation will be filled manually for now.

I have already written a simple text processing script in python:

 import requests def get_translation(text, lang): URL = 'https://translate.yandex.net/api/v1.5/tr.json/translate' KEY = 'trnsl.1.1........' TEXT = text r = requests.post(URL, data={'key': KEY, 'text': TEXT, 'lang': lang}) return eval(r.text)['text'] str = "Hello world!!!!" print(*get_translation(str, 'ru')) 

But when trying to transfer it to Django, there are difficulties. Is it possible to write a method in models.py that translates text? Or maybe there are other ways? Thank!

  • Describe your question more specifically. What exactly are the difficulties when transferring to Django? In models.py it is quite possible to write a method that would translate the text. It can also be written in other places. This is how you want to do it. - Nikita Konin

1 answer 1

First, you need to specify in the models that the translated text may be absent (the reasons for this may be different).

We are upgrading the model:

 from django.db import models from ckeditor.fields import RichTextField import requests class Translations(models.Model): text_origin = RichTextField() lang_text_origin = models.CharField(max_length=10) text_translation = RichTextField(blank=True) lang_text_translation = models.CharField(max_length=10) 

In django, there are signals that run at certain times, for example, before calling the save method. It is called pre_save . You can create a signal that, before the model is saved, will fill in the data.

For example, like this:

 from django.db.models.signals import pre_save from django.dispatch import receiver @receiver(pre_save, sender=Translations) def my_callback(sender, instance, *args, **kwargs): instance.text_translation = get_translation(str, 'ru') 

Supplement, if you need to create a translation only in the admin panel, you can override the save_model method in the admin panel . For example:

 class MyAdminView(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.text_translation = get_translation(str, 'ru') super(MyAdminView, self).save_model(request, obj, form, change) 
  • redefined the save_model method in the admin panel, everything works, thanks! - Mikhail Kovalev