I am trying to translate my webpage using django-modeltranslation. I have complete the setup with the help of documentation provided but I am facing problem to display the model translated fields to templates. Can you help?
Here is what I have done.
# settings.py
def gettext(s):
return s
LANGUAGES = (
('en', gettext('English')),
('de', gettext('German')),
)
MODELTRANSLATION_TRANSLATION_FILES = (
'main.translation',
)
in app translation.py file
# project/app/translation.py
from modeltranslation.translator import translator, TranslationOptions
from .models import Post
class PostTranslationOptions(TranslationOptions):
fields = ('title', 'description')
translator.register(Post, PostTranslationOptions)
project urls.py file.
# urls.py
from django.contrib import admin
from django.urls import path, include
import debug_toolbar
from django.conf.urls.i18n import i18n_patterns
urlpatterns = [
path('admin/', admin.site.urls)
]
urlpatterns += [
path(r'^__debug__/', include(debug_toolbar.urls)),
]
urlpatterns += i18n_patterns(path('', include('main.urls')))
Views.py
# views.py
def ceo_dashboard(request):
post = Post.objects.all().select_related()
return render(request, 'main/dashboard_page.html', {'user': request.user, 'Posts': post})
template file
<h2 style="color:#0B2161;" >{{ post.title }}</h2>
<hr>
<p>{{ post.description }}</p>
<h5>Uploaded by : {{post.user}}</h5>
<hr>
Now I have no idea how to display these fields to templates.
You also need to add a Middleware called LocaleMiddleware, which activates translation for your project:
Read more about it in the Django documentation here: How Django discovers language preference
After that, you also need to add the language re-directer in your main template:
Now you can go to your admin and add Post where the django admin asks to enter different translation into the appropriate forms for the specified fields (in your case, 'title', 'description')
Hope this help you to solve the problem!