I am making a multilingual Django website. I created a messages file, populated and compiled it. I checked the site (the admin in this case,) in my wanted language (Hebrew) and most phrases appear in Hebrew like they should, but some don't. I checked the source and these still appear as _('Whatever') like they should, also they are translated on the messages file, and yes, I remembered to do compilemessages.
What are some common causes for translations not to appear like that?
Maybe the translated strings are marked as fuzzy?
Just got hit by one. I had the locale/ directory in the root of my project, but by default Django looks for translations in the INSTALLED_APPS directories, and in the default translations. So it didn't find the translations I added. But some of my strings were in the default translations that come with Django (eg "Search") so a few strings were translated, which confused me.
To add the directory where my translations were to the list of places that Django will look for translations, I had to set the LOCALE_PATHS setting. So in my case, where the locale/ directory and settings.py were both in the root of the django project I could put the following in settings.py:
from os import path
LOCALE_PATHS = (
path.join(path.abspath(path.dirname(__file__)), 'locale'),
)
I'm trying to provide a complete check list:
In settings.py, are USE_I18N, USE_L10N, LANGUAGE_CODE, and LOCALE_PATHS set properly?
See this list for all allowed values of language identifiers. Note that Simplified Chinese is specified by zh-hans, not zh-cn.
In settings.py, is django.middleware.locale.LocaleMiddleware included in MIDDLEWARE in correct order?
Have you (re)run django-admin makemessages -l <locale-name> with the correct local name, from the correct place?
You can see an incomplete list of allowed locale name by running ls your/path/to/python/site-packages/django/conf/locale/ on your machine, or by taking a look at the source code
Note that you have to use _ rather than - here. For example, to specify simplified Chinese, execute django-admin makemessages -l zh_Hans, not zh_CN or zh_hans or zh-Hans or anything else.
Have you removed all fuzzy tags in your PO file(s)?
Have you (re)compiled the OP file(s) with django-admin compilemessages?
Have you restarted the web server?
Additional notes:
If some of your translation is overridden by Django's default translation, use contextual markers to bypass it. For example,
models.py
first_name = models.CharField(
pgettext_lazy('override default', 'first name'),
max_length=30
)
last_name = models.CharField(
pgettext_lazy('override default', 'last name'),
max_length=150
)
django.po
#: models.py:51
msgctxt "override default"
msgid "first name"
msgstr "姓"
#: models.py:55
msgctxt "override default"
msgid "last name"
msgstr "名"
and you'll see 姓, 名 instead of the default 姓氏, 名字.
I was having this problem with my project right now. I had the variable LANGUAGES on settings.py set this way:
LANGUAGES = (
('en', _('English')),
('pt-br', _('Brazilian Portuguese')),
)
And a folder structure with a locale folder, and a subfolder pt-br inside. Turns out that my translations weren't loading. The LANGUAGES variable follows the pt-br pattern, and the folders must be on pt_BR pattern. At least that's the only way it's working here!
Hi just attach some fixes I had to do in the past:
Restart the webserver!
In the setting file
- USE_I18N = True is needed
django.middleware.locale.LocaleMiddleware among middleware modules (but this is not your case for sure as long as Django will not care about your local at all)
django.core.context_processors.i18n among TEMPLATE_CONTEXT_PROCESSORS
for sure I had other issues related to translations but I don't remember them all... hope this can help!
A possible cause is Lazy Translation.
In example, in views.py you should use ugettext:
from django.utils.translation import ugettext as _
But in models.py, you should use ugettext_lazy:
from django.utils.translation import ugettext_lazy as _
Another cause can be a wrong directory structure.
Read well the manage command's error message about which directory to create before running the makemassages command for the app translation. (It must be locale for an app, not conf/locale.) Note that the management commands work fine even with the wrong directory structure.
I noticed that when I had % in my text, the translated text was not being used. There may be other characters that can cause this problem. I fixed the problem by escaping the % as %%.
My answer here, all my translations were working except for 2 DateFields that I was using in a ModelForm.
Turns out that I had a widget in my forms.py that was not working well with the translations.
I just removed it for now so I can enjoy Xmas =D
Related
I have a problem with translations in Project module. Some menu items are not translated. What could be the problem?
Here project_view.xml
<!-- Top menu item -->
<menuitem name="Project"
id="base.menu_main_pm"
groups="group_project_manager,group_project_user"
icon="fa-calendar"
web_icon="project,static/description/icon.png"
sequence="50"/>
Here ru.po
#. module: project
#: model:ir.model,name:project.model_project_project
#: model:ir.model.fields,field_description:project.field_project_task_history_cumulative_project_id
#: model:ir.model.fields,field_description:project.field_project_task_project_id
#: model:ir.model.fields,field_description:project.field_report_project_task_user_project_id
#: model:ir.ui.view,arch_db:project.edit_project
#: model:ir.ui.view,arch_db:project.view_task_form2
#: model:ir.ui.view,arch_db:project.view_task_history_search
#: model:ir.ui.view,arch_db:project.view_task_project_user_search
#: model:ir.ui.view,arch_db:project.view_task_search_form
#: model:res.request.link,name:project.req_link_project
msgid "Project"
msgstr "Проект"
I've also had this problem with translations. I had updated module base a lot of times too and it worked, but sometimes it wasn't necessary. What I did is the next process:
Go to Settings > Translations > Load a Translation, select your
language and check the box Overwrite Existing Terms, then click on
Load button.
After that, press F5 to refresh the browser, then go to Settings >
Translations > Application Terms > Synchronize Terms, select your
language and click on Update. Then press again F5 to see if your
terms have been updated.
Regards.
Sometimes translations don't work very well. Try pressing the "Update" button in the "Base" module. This should solve the problem.
Update: 21 nov 2019
I do not know in older versions, but now there are more options in command line to update, import and export translations. The argument --i18n-overwrite might be useful in your case:
Use these options to translate Odoo to another language. See i18n
section of the user manual. Option '-d' is mandatory. Option '-l' is
mandatory in case of importation
--load-language=LOAD_LANGUAGE
specifies the languages for the translations you want
to be loaded
-l LANGUAGE, --language=LANGUAGE
specify the language of the translation file. Use it
with --i18n-export or --i18n-import
--i18n-export=TRANSLATE_OUT
export all sentences to be translated to a CSV file, a
PO file or a TGZ archive and exit
--i18n-import=TRANSLATE_IN
import a CSV or a PO file with translations and exit.
The '-l' option is required.
--i18n-overwrite overwrites existing translation terms on updating a
module or importing a CSV or a PO file.
--modules=TRANSLATE_MODULES
specify modules to export. Use in combination with
--i18n-export
Sometimes, is not enough to update the base module. I implemented a solution based on a post. What I do is clear the whole language using a query, and then reload the language again using. "Load a Translation" from config menu.
The query that made it possible, is the following, for example for es_CL:
DELETE FROM ir_translation WHERE lang = 'es_CL';
I've put this in a module, which you can use to adapt it to your needs:
https://github.com/odoo-chile/l10n_cl_clear_translation
When this module is instaled it runs the query. Then you can reload your language using the menu.
Yes, sometimes the localization doesn't work perfectly. Here's another strategy from v8, which may still help you in v9.
First, update your module like described
Then, remove all translated strings for your module from the database. This is safe, because you have them in your ru.po file.
Go to Settings > Translations > Application Terms > Translated Terms
Do an "Advanced Search" with 'Module' 'contains' to find all your terms
select them all (possibly set the pager to 'unlimited')
Select 'More' > 'Delete'
Confirm
Update your module again.
Export the ru.po file again; it should now contain all missing terms.
The issue seems to be that the module sometimes takes some values from the default (en) language into the target language, which then prohibits the term to be listed as 'to be translated'.
I have API interface for my application and want the response of these calls to support various languages.
def get_student(request):
//code
return JsonResponse(content={"Message": "student is found"}, status=200)
I have gone through django-localization documentation and have created a po and mo files for specific language.
And now i'm stuck on how to use those files and give the response in particular language.
any help or reference will be appreciated.
EDIT: this one helped
settings.LOCALE_PATHS = (os.path.join(PROJECT_DIR, 'locale'))
and
https://docs.djangoproject.com/en/1.3/howto/i18n/
Before you worrying about .mo and .po files, you need to set up the various flags, languages and middlewares in your settings, and mark translatable text in your apps and templates.
You should start here https://docs.djangoproject.com/en/1.3/topics/i18n/ for the big pictures and definitions, then continue here https://docs.djangoproject.com/en/1.3/topics/i18n/translation/ for how to mark the translatable strings. Don't skip the notes as there are some configuration job to do.
About how to mark as string as translatable, in your above snippet, it should looks like:
from django.utils.translation import ugettext as _
def get_student(request):
//code
return JsonResponse(content={"Message": _(u"student is found")}, status=200)
Once you're done with marking all your translatable texts, it's time to generate the source translation files (.po), edit them with the actual translations and finally generate the compiled translations files (.mo) as documented.
I'm attempting to customize the parser/lexer for the httpdomain Sphinx doc extension. I installed in a given dir and added the dir to the sys.path as mentioned in the docs.
I then compile the Sphinx doc and http gets highlighted properly.
Now, I need to make a small change to the extension. I started by making a random change to the httpdomain.py file inside the extension's dir, which correctly yielded an error for invalid syntax.
Next, I changed the lexer by replacing the HTTP token with HTTTP (one extra T). My idea is to see if now entries in the doc containing HTTTP get highlighted instead of HTTP.
The issue is that nothing I do seems to change the output. HTTP continues to get colored, and HTTTP is ignored.
Here is the section of the lexer that contains my change:
tokens = {
'root': [
(r'(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|TRACE)( +)([^ ]+)( +)'
r'(HTTTPS?)(/)(1\.[013])(\r?\n|$)',
bygroups(Name.Function, Text, Name.Namespace, Text,
Keyword.Reserved, Operator, Number, Text),
'headers'),
(r'(HTTTPS?)(/)(1\.[013])( +)(\d{3})( +)([^\r\n]+)(\r?\n|$)',
bygroups(Keyword.Reserved, Operator, Number, Text, Number,
Text, Name.Exception, Text),
'headers'),
(r'([^\s:]+)( *)(:)( *)([^\r\n]+)(\r?\n|$)', header_callback),
(r'([\t ]+)([^\r\n]+)(\r?\n|$)', continuous_header_callback),
(r'\r?\n', Text, 'content')
],
'headers': [
(r'([^\s:]+)( *)(:)( *)([^\r\n]+)(\r?\n|$)', header_callback),
(r'([\t ]+)([^\r\n]+)(\r?\n|$)', continuous_header_callback),
(r'\r?\n', Text, 'content')
],
'content': [
(r'.+', content_callback)
]
}
Note that "HTTP" is changed to "HTTTP", so I'd expect entries in the doc containing HTTTP now to be colored, but nothing changed.
I made changes to the doc text and saw they were updated in the page, so no cache issues there.
I also deleted a folder Python created called __pycache__, no changes to the result. I also trying commenting out all tokens in the lexer, no changes. If I insert invalid syntax, then it fails. If the syntax is correct, it seems like it uses the original code without my changes.
Is there any other cache I should be clearing up?
I'm totally new to Python so I'm a bit lost here.
PS: this HTTTP thing is just a test. I'll make the real changes once I get this to work.
It turns out the code changes were being seen, but the lexer was never used because Pygments also registered a lexer called html. So I replaced it with mine: app.add_lexer('http', HTTPLexer()) and I started seeing my changes affecting the generated docs.
Try to remove *.pyc files and restart your extension
I have a list of languages for my django project and they work perfectly:
LANGUAGES = (
('en', ugettext('English')),
('es', ugettext('Spanish')),
)
Now I want to add English UK because some users wrote me about spelling errors that aren't really errors, just the difference between both UK and US english, so I added:
LANGUAGES = (
('en', ugettext('English')),
#('en-us', ugettext('English US')),
('es', ugettext('Spanish')),
('en-gb', ugettext('English UK')),
)
and did all the process to create the language files, but when I select the 'en-gb' it just uses the same files as 'en'. Notice that I try using both 'en' and a new 'en-us'
I tried to add 'fr' to the list and use the translation files I have for 'en-gb' and they work perfectly.
How can I make the 'en-gb' work? I could just use a language code that I'm probably never going to use and put my files there, but that does not seem the right way to do it and I'm probably just missing something simple to make the 'en-gb' work.
It should be en_GB, not en-gb. See the docs.
I have tried to get this to work a million times. I have lef it alone for a week and come back. I have Googled and read every post pertaining to this. I have let insecure morons belittle in messages groups without ever finding the answer. I just want this to work. When I am following along in part three of the the Django tutorial, I get to the part where you make the template for the index page, and when I go to check it in the browser, it comes up with TemplateDoesNotExist at /polls/. I have checked file ownership, moved it all around, always changing the TEMPLATES_DIR in setting.py. I have pipe'd the contents of the file to cat to make sure it works. I have scarificed animals to strange Gods to get this to work. I turn to you now. I am sure it is the stupidest thing ever, I have very little doubt about this. I just want it to work.
I am not sure what parts of the code/traceback you want/need here, let me know I will post them. I am doing this on Ubuntu 10.10
EDIT
From settings.py:
TEMPLATE_DIRS = (
"home/kevin/first/tutorial/temps"
)
This used to live in ~, but I moved into the project folder thinking it would help.
Structure(leaving out all complied python files):
~/first/tutorial/:
__init__.py,
manage.py,
polls,
settings.py,
temps,
tut.db,
urls.py
temps:
index.html
polls:
admin.py,
__init__.py,
models.py,
tests.py,
views.py,
>>> TEMPLATE_DIRS = ( "home/kevin/first/tutorial/temps" )
>>> print TEMPLATE_DIRS
home/kevin/first/tutorial/temps
>>> type(TEMPLATE_DIRS)
<type 'str'>
This is a string, not a tuple.
TEMPLATE_DIRS = ( "home/kevin/first/tutorial/temps", )
That is a tuple. A little bit of a Python gotcha.
Furthermore, use an absolute path rather than a relative path.
First off, and this might not be relevant to your problem, but it's good practice to not use absolute paths in your files. I always have the following in my settings.py:
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, 'templates'),
)
You should always have a comma at the end of an element in your tuple, even if it is the only one or the last one, so that Python actually considers it to be a tuple and not evaluate to any other type.
You should also make sure that your TEMPLATE_LOADERS setting contains or looks like this:
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
If that doesn't fix it (you should still keep the above in regardless), the problem is most likely related to the template you're rendering to. Confirm that the string of the template you're using in the view corresponds correctly to the relative path of the template within your templates directory. In other words, if the template string is 'polls/index.html' in your view, ensure that the file is actually located at templates/polls/index.html.
What I've used in my settings.py configuration file was:
"TEMPLATE_DIRS = (
'/path/to/folder/Python-templates',
)"
And it worked. What I guess (and correct me if I'm wrong) is that the example in the django tutorial is making reference to the exact location of the template within the templates folder, which is polls. Thus, in the example found in this tutorial, the polls/index.html path to file is saying "the index.html file in the polls folder that is already in the template folder specified in settings.py".
This happened to me because I skipped to part three (I wanted to learn about templates) and I forgot to add add the PollsConfig to INSTALLED_APPS
Your mysite/settings.py should look this this:
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
After I did this change, the templates were all found.
This is a bit confusing because you don't have to do this to make your views work. But templates definitely won't load if your app's config is not in INSTALLED_APPS.
Some things to check:
Do you use an absolute path to specify the template directory in settings.py?
Did you put the template directly into the TEMPLATE_DIR directory, or did you make a polls subfolder to put the template in?
I had the same issue as you described, doing the third part of the Django tutorial throws TemplateDoesNotExist.
Restarting the server solved it for me (did not change any configurations). Hope that helps...