Django i18n is not detecting texts inside the for loop

39 Views Asked by At

I couldn't understand why the i18n is not detecting the data in my loop:

{% trans service.title %}

anyone who can help!? Thanks in advance!

{% load i18n %}

{% for service in services %}
                <div class="col-sm-3">
                    <div class="service bg-white">
                        <div class="img-block">
                            <img alt="" class="service-img img-fluid"
                                src="{{service.img.url}}">
                        </div>
                        <div class="service-feature">
                            <h4 class="feature-text text-center">
                                {% trans service.title %}
                            </h4>
                            <p>{{service.desc}}</p>
                        </div>
                    </div>
                </div>
{% endfor %}

I tried several different ways such:

{% translate service.title %} no reactions

{{ service.title|trans }} no reactions

1

There are 1 best solutions below

0
Mihail Andreev On BEST ANSWER

It seems like your content is coming from the database and is dynamic, traditional string-based translation won't work as intended.

Django doesn't have built-in support for database content translation, but there are third-party packages available that can help. One of the most popular is django-modeltranslation. Here's how to use it:

  1. Install django-modeltranslation:
pip install django-modeltranslation
  1. Add it to your INSTALLED_APPS:
INSTALLED_APPS = [
    ...
    'modeltranslation',
]
  1. Set Up Translations in your Model: Suppose you have a model like this:
class Service(models.Model):
    title = models.CharField(max_length=200)
    desc = models.TextField()
    ...

To add translations for the title and desc fields, you'd create a translation.py in the same app directory:

from modeltranslation.translator import register, TranslationOptions
from .models import Service

@register(Service)
class ServiceTranslationOptions(TranslationOptions):
    fields = ('title', 'desc')
  1. Migrate the database: After setting up translations for your model, you need to create and apply migrations to add columns for each language you're supporting:
python manage.py makemigrations
python manage.py migrate
  1. Use in Templates: In your template, when the appropriate language is active, the translated version of the fields will automatically be used. So you can simply do:
{{ service.title }}
{{ service.desc }}
  1. Admin Integration: django-modeltranslation also supports integration with the Django Admin, providing tabs for each language where you can input translated content.

Remember to always read the documentation of third-party packages and test them to make sure they work as expected and satisfy your requirements.