I'm working on a Django CMS with content to be translated into multiple languages. I'm using django-parler.
To make the translations easier I would like to have the text from the default language visible when adding the translated text, preferable just above the input field/textarea.
Any ideas on how to solve it?
You can override the get_form
method in the Admin class, and update the widgets placeholder
attribute. For example, if I have the folllowing model:
from django.utils.translation import gettext_lazy as _
from parler.models import TranslatableModel, TranslatedFields
class KeyCard(TranslatableModel):
translations = TranslatedFields(
series=models.CharField(_('series'), max_length=255, blank=True, null=True),
skill=models.CharField(_('skill'), max_length=255, blank=True, null=True),
)
Then I can use
from django.contrib import admin
from parler.admin import TranslatableAdmin
from parler.utils.context import switch_language
@admin.register(KeyCard)
class GuideAdmin(TranslatableAdmin):
def get_form(self, request, obj=None, **kwargs):
form = super().get_form(request, obj, **kwargs)
with switch_language(obj, 'de'):
for field in ['series', 'skill']:
form.base_fields[field].widget.attrs['placeholder'] = getattr(obj, field)
return form
Where de
is my default language, and the fields series
and skill
are translatable fields.
Now this creates placeholders
, which will disappear when typing, alternatively you can use:
form.base_fields[field].widget.attrs['value'] = getattr(obj, field)
To get the actuall value there, such that you can directly save it.
Now if you don't want to keep track of the translatable fields yourself, you can use:
for field in obj._parler_meta.get_all_fields():
form.base_fields[field].widget.attrs['placeholder'] = getattr(obj, field)
Which will get you all translatable fields.
Note:
value
won't work on models.TextField