Search code examples
djangodjango-modelsdjango-templatestranslation

Translation from data in database


I implemented a logs system in my Django app, this system, for every action of any user will save informations in the database. Here is the model:

class Log(models.Model):
    user = models.ForeignKey(to=User, on_delete=models.PROTECT)
    log = models.CharField(max_length=255)
    type = models.CharField(max_length=50)
    date = models.DateTimeField(auto_now_add=True)
    company = models.ForeignKey(to=Company, on_delete=models.PROTECT)

My point is on the translation of the log field. For exemple my language is english, it will save in the database "did create a new customer", But if I change the language in french I will obviously get this in english again. Same if a french create a log I will have some logs in french others in english. My problem is there is hundreds of different possibilities for this log field.

Is it a way with Django to translate data coming from the database in the templates like with a {% translate %} tag?

I was thinking something like having these hundreds possibilities in the translation files and Django translate it directly in the templates?

I do have the same problem with the permissions name. Users can give permissions to other users but these permission names are in english.

Thanks for your help


Solution

  • Yes - Django has an inbuilt method for this .gettext() as described in the docs: https://docs.djangoproject.com/en/3.1/topics/i18n/translation/

    This will translate the string into the end user's language. You can use it within templates or within your models.

    To use it within your template:

    <!-- load i18n -->
    {% load i18n %} 
    
    <!-- translate text -->
    <title>{% translate "This is the title." %}</title>
    
    <!-- translate string variable passed from context -->
    <title>{% translate myvar %}</title>
    

    In templates, translate calls .gettext() on the string under the hood.

    Hope this helps ;)

    Extra info:

    Django's LocaleMiddleware will attempt to detect which language it is translating to (via a variety of techniques which you can read on the doc link).

    However, if the middleware cannot detect which language the end user wants, it will use the language specified in the LANGUAGE_CODE variable in settings.py. This is the default language that Django will translate to.