I have an application where users can fill a text field.
I would like "try" to translate it if the string that the user entered is in the .po translation files.
So in one of my detail views, I did something like:
class InterrogationDetailView(generic.DetailView):
model = Interrogation
def get_context_data(self, **kwargs):
context = super(InterrogationDetailView, self)\
.get_context_data(**kwargs)
if self.object is not None:
context[u'translated_word'] = {
u'description': _(self.object.description),
}
return context
That's nice, it seems to work. So it searches in the .po files. So I'd like to add sentences, or words on my own in those .po files. When I try to add one translation that is not in my source files, when I call makemessages I get them commented like:
#~ msgid "I'm a test"
#~ msgstr "Godsmack - Cryin' like a b"
How to solve this? And if I'm not doing this the right way (I've read a lot about django translation), what is the way to go?
Django documentation mentions that makemessages is not capable of extracting translations for computed values, as happens in your example.
In order to have translations for strings that you retrieve from somewhere else you have to have them in your code as string literals. This can be achieved by the way #psychok7 suggests, creating a separate .py listing all those strings.
One way to automate this could be to write your custom django-admin command that will retrieve strings to be translated from database and put them into some file, locatable by makemessages, e.g. .txt with translation tags.
Related
So I have a website which is using the Wagtailtrans extension for Wagtail. I basically enables multi language by duplicating the page tree. So the url gets fixed with the language-code at the start.
I can translate all my content which I define through my models perfectly fine. Here's an example of how that works:
class ServicesPage(MetadataPageMixin, TranslatablePage):
description = models.CharField(max_length=255, blank=True,)
content_panels = Page.content_panels + [
FieldPanel('description', classname="full")
]
Instead of Page you define it as TranslatablePage in your model. All is working fine, however I still need some additional strings which I don't define in my models to be translated. I just use Django's translation feature with {% load i18n %} and then the strings wrapped inside {% trans "String" %}.
So far so good, I defined my two languages in Wagtail admin (Wagtail trans creates an option for that) which in this case is English and Dutch. I set English as the main language so the strings are in english.
I use ./manage.py makemessages and it creates a .po file for me, with all the tagged strings in there. At last I use ./manage.py compilemessages.
But translated strings are not showing up when I switch to Dutch language, it still displays the english strings. So I suspect it needs some additional tweaking to work with Wagtailtrans, but I can't seem to figure out how this set-up should be. Can anyone help me out?
I want to translate in any language django permission names. To do this i extend django.contrib.auth.models.Permission model in django like this :
class ExtendedPermission(Permission):
translation_name = models.CharField(_('translation_name'),max_length=255)
Then i want to update this table in management commands. First 'name' field taken from Permission model, than it must be translated into another language for instance tr to use in ExtendedPermission model as translation_name field.This function in management/commands:
def try_translate(self,permission):
translation.activate(settings.LANGUAGE_CODE)
translation.activate('tr')
translated_str =translation.ugettext(permission)
translation.deactivate()
return translated_str
When run this command the variable does not appear in .po file.But if i give string that i want to translate like this :
ugettext("name")
msgid = "name" appears in .po file and i can edit msgstr but i can not get the translated msgstr from .mo file with using ugettext.
I add 'django.middleware.locale.LocaleMiddleware', to settings file.I also run commands makemessages and compilemessages.
As I understand it, the Django i18n support works off static data, which you pre-generate running makemessages. It looks for _(), {% trains %}, etc, which require static strings.
If permissions is not know statically ( e.g. Without reading a database ), then it cannot process it during makemessages.
I have a drupal English/French website.
I have a custom content type called 'ad' with all sort of fields.
I have created the file 'node--ad.tpl.php' in my theme directory
to customize the display of the 'ad' content.
I use pixture reloaded theme and DRUPAL 7.
I am trying to translate fields (both labels and values)
by using 'field translation' module.
Field translation works when I CREATE or MODIFY a content via admin.
However, when I DISPLAY a content of type 'ad', fields are not translated.
This is because drupal calls to 'node--ad.tpl.php' and the translation
module is probably not invoked.
When deleting 'node--ad.tpl.php', drupal calls the default node.tpl.php
with a similar results.
Any help would be appreciated,
Thanks in advanced,
Notes :
1 - I correctly activated every dependencies for the module.
2 - User interface translation correctly works.
OK
I found out myself how to do this.
I give the solution here.
It may help for others :
First, translate field labels and values in Configuration > Regional and language > Translate > Import. Do not import values as Fields but as User Interface. Do not specify
an URL (only msgstr and msgid).
Now, you need to add your t() function in the node.tpl.php for the translation to be effective. So :
In the node.tpl.php file, if you want to translate field label, write this :
$content['field_my_field']['#title'] = t($content['field_my_field']['#title']);
Then to translate field value do this :
$content['field_my_field']["#items"][0]['value'] = t($content['field_my_field']["#items"][0]['value']);
You can now render your field : print render($content['field_my_field']);
I am using .mo files for localization in Django.
Also, in my database, I store some translated text in different fields, such as:
name_en, name_es, name_de (they are all columns in each row).
What will be the best method to choose the correct field inside a template?
i.e.:
{{ name.some_method }} will generate the correct translation based on the current localization.
Thanks,
Meit
You should look at http://goodcode.io/articles/django-multilanguage/ Here’s a simple solution that may fit your use case and is easy to implement and understand.
You should look at Django Transmeta, it work the same way as what you've done (DB fields with language code) but it's a more complete solution. It already deal with the template stuff, etc.
You can check Model Internationalization and Django Packages for more info and ideas in this domain.
I can see two method for doing this, one in your view and the other one is in the template...
In view:
Probably you keep the user language information somewhere so,
user_lang = 'es'
obj = Somemodel.objects.get(pk=123434)
obj.local_name = getattr(obj, 'name_%s'%user_lang)
So, you keep local translation in a specific variable of the instance and in your template you can use is as:
{{obj.local_name}}
But that might be costly if you wish to pass the template a queryset instead of a single instance. For a such usege you have to evaluate that value for each object in your queryset.
In template:
That is a more complex way of solving the porblem in the template...
Define a template tag and pass object_id, and local language information and get the translated text using a similar getattr function. But in that point, if you wish to use this for more than one model, you probably have to pass a content type information for your template tag too, such as:
{% get_translation <object_id> <content_type_id> <local_language> %}
And in your template tag function, do something like:
from django.contrib.contenttypes.models import ContentType
....
cont_obj = Content_type.objects.get_for_id(<cotent_type_id>) #get the related model
obj = cont_obj.get_object_for_this_type(pk=<object_id>) # get your object
return getattr(obj, 'name_%s'%<local_language>)
In my models.py file I define a field on a model like this:
description = models.CharField(
max_length=40,
default=_('Bla bla bla'),
)
Now, _ is django.utils.translation.ugettext, and I want to use as a default value the Hebrew translation of 'Bla bla bla', which is 'בלה בלה בלה'. (The website is in Hebrew only.) The string is properly translated in the messages file. But when I run the Django admin and create a new object, I see the English 'bla bla bla' on the field. I assume that English is the active language when compiling the models.py module. How can I solve this and make it Hebrew?
I know that one solution would be to forego ugettext and just write Hebrew inside the Python module, but I prefer to avoid that in order to prevent encoding hell.
Try ugettext_lazy
https://docs.djangoproject.com/en/1.3/topics/i18n/internationalization/#lazy-translation
Always use lazy translations in Django
models.
ugettext merely marks strings as translatable. It doesn't do any translation for you, per se. You have to create language files (.mo and .po) and then set the LANGUAGE_CODE setting to match. Read the Django documentation on Internationalization and Localization for more in depth info.