i am a new to Django, i am trying to make a small blog with two different languages, i got all the translations inside my blog including the admin, but still don't know how to translate the content of my posts.
After i fetch the content using the models queries, inside my template i used to type this {% trans "SOME TEXT" %}
and it works just fine, with variables that i am getting from database i am using this code:
{% blocktrans %}
{{head.title_text}}
{% endblocktrans %}
now when i type django-admin makemessages -l ru
, inside django.po i can't see any new text that have been added.
Also inside my views.py i tried this:
head = Head.objects.first()
trans_h = _(u'{}'.format(head))
but nothing gets added inside django.po
Please, anyone knows how to resolve this issue ??
I think the best way to translate the content of the Post Model without using any third-party is to create for each fields you need to translate inside your models with different languages and translate them from your admin,and display them in your template when the site change the language, in Django you can translate only the text you can not translate the data from your model
Create your model Post
models.py
class Post(models.Model)
title_fr = models.CharField(max_length=200)
title_en = models.CharField(max_length=200)
content_fr = models.TextField()
content_en = models.TextField()
created_at = models.DateTimeField(auto_now_add=True, auto_now=False)
updated_at = models.DateTimeField(auto_now_add=False, auto_now=True)
In the view you translate the text inside the variable and pass it in your template
views.py
from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse
from .models import Post
from django.utils.translation import ugettext_lazy as _
def post_view(request):
post = Post.objects.all()
# Here is you can translate the text in python
title = _("les meilleurs posts du mois")
context = {
'post':post,
'title':title
}
template = loader.get_template('index.html')
return HttpResponse(template.render(context, request))
Here the idea is once your site is translated in french for example(www.mysite.com/fr/) in your template you will get only the attributes with _fr(title_fr, content_fr) already translated in your admin and if it's in english it will be the same thing
index.html
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_available_languages as LANGUAGES %}
<h1> {{ title}}</h1>
{% if LANGUAGE_CODE|language_name_translated == 'Français' %}
{% for items in home %}
<h2>{{ items.title_fr }}</h2>
<p> {{items.content_fr}}</p>
{% endfor %}
{% if LANGUAGE_CODE|language_name_translated == 'English' %}
{% for items in home %}
<h2>{{ items.title_en }}</h2>
<p>{{items.content_en}}</p>
{% endfor %}
{% endif %}
I hope it can be helpful