Variable translation in django - django

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.

Related

How can I use Django's translation strings with Wagtailtrans (Add-on for supporting multi language Wagtail sites)

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?

Django translation in 1.9

I have a django project with one translation (call it 'en').
I have a simple menu for a user to select the language.
I used to do this:
If he selected the 'en' option, I would do:
request.session[translation.LANGUAGE_SESSION_KEY] = 'en'
and that would work.
If I wanted to disable the 'en' translation, I would do:
request.session[translation.LANGUAGE_SESSION_KEY] = ''
and that would restore the template original language.
Means if I have this in template:
{% trans "some non english text" %}
then setting the session cookie to '', would show the original text (no trans), which is what I wanted.
All of this true for django 1.7.
In django 1.9, this simply won't work, setting the session cookie language key to '', still keep the active translation.
How do I disable the translation correctly? I just want to show the website in its default language (output the template as is, no translation file).
EDIT, SOLUTION:
It worked differently in django < 1.8. Since 1.8 setting the session key to empty string does not mean "fallback to no translation". So what I did is to set the LANGUAGE_CODE setting to a code which I dont have a translation file for. That simply cause the template to appear as is.

Django translation: add custom translation

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.

Translating fields in node.tpl.php file with drupal 7

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']);

Using `ugettext` in a definition of a Django field

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.