I installed python separated from yum.
Now, I need to recompile the language pack for the OSQA system, but get this message:
Error: errors happened while running xgettext on __init__.py
xgettext: ./Django-1.2.3/tests/regressiontests/views/__init__.py:1: Unknown encoding "utf8". Proceeding with ASCII instead.
xgettext: Non-ASCII string at ./Django-1.2.3/tests/regressiontests/views/__init__.py:7.
Please specify the source encoding through --from-code or through a comment
as specified in http://www.python.org/peps/pep-0263.html.
I tried to set encode at utf-8 in the manage.py file but it didn't work.
Can someone help me to solve this issue?
I know this post is outdated but I had the same issue today, and it took me hours to find out why. Maybe people will be in the same case :
My virtualenv is in my django root directory :
Here is my project tree :
DjangoDirectory:
my_env
Django_App1
Django_App2
...
...
manage.py
When I launch command :
./manage.py makemessages -l fr
I get the same error :
Error: errors happened while running xgettext on __init__.py
...
In fact, I noticed that xgettext looked into ALL the files in my folder, as well as files in my_env.
So I found the -i flag which ignore files or folders during the makemessages process
So now, with the command below it works like a charm and I don't get the error anymore.
./manage.py makemessages -l fr -i my_env
Hope it will help
Actually yes, I've already had similar problems with makemessages, because on top of every source file I wrote "# coding: utf8". Even though it worked with source compilation, I've had to replace "utf8" with "utf-8" in every file.
If you're not used to makemessages, take care of gettext functions applied to format strings, you will need strings to contain named parameters when there is more than one placeholder.
"%s" is good
"%(max)s" is good too
"%(min)s %(max)s" too
"%s %s" is not ok.
Actually if you did all the configurations correctly in settings.py, views and templates and you installed gettext and all good, then you may want to check where your virtual environment is. For instance if it's inside your root folder in your project folder your structure I suppose is myapp_project/venv/
Also I'm assuming you've you created an empty folder called locale in your root myapp_project folder.
Try to run it like this if you're translating french for example:
and note: replace venv with whatever you named your virtual environment.
This is the short answer
django-admin.py makemessages -l fr -i venv
this above will get you the local/fr/LC_MESSAGES/django.po but you now have to run the second command to compile the .po file created by makemessages to a .mo file in the LC_MESSAGES folder
So, then run:
django-admin.py compilemessages
now this should get you the django.po file.
This is the long answer
If you configured your urls.py correctly with i18n_patterns, and you filled the translations of msgstr "" in your .po file and then run django-admin.py compilemessages again you can now run your server and go to your desired page 127.0.0.1:8000/fr/ and you should see your translations.
In case you are wondering what your settings.py file should look like (for french). It should look like this at least part of it.
from django.utils.translation import gettext_lazy as _
LANGUAGES = [
('fr', _('French')),
('en', _('English')),
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LOCALE_PATHS = [
os.path.join(BASE_DIR, 'locale'),
]
Also in settings.py in the MIDDLEWARE list make sure you add the component. 'django.middleware.locale.LocaleMiddleware' and it's important where on the list you put that component as it executes from top to bottom. So put it under the sessions component.
For your main app (you may have a few or one) urls.py file make sure you import from django.conf.urls.i18n import i18n_patterns.
Next on the same urls.py file ensure that you actually add/or edit the url patterns alright. Here is an example of what it could look like:
urlpatterns += i18n_patterns (
path('', include('pages.urls')),
path('meals/', include('meals.urls')),
prefix_default_language=False
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
You can play with this and obviously on the paths above it don't include the admin. So just play around but just giving you an idea of what it should look like in order for /fr/ url to work.
You will also notice above the line prefix_default_language=False this is to prevent the /en/ default pattern. In this example we are translating from English to French. So no need to have /en/ in the pattern.
Don't forget in your templates... yes all of them, it don't matter if it's parent template or not. You have to include {% load i18n %} for this to work.
Important to Note:
When you go back to your templates files and you start updating your text content and adding your transblocks etc. After you do this. Go back to your terminal and stop your server, and again if you have your venv folder in your root you must run these commands:
django-admin.py makemessages -l fr -i venv
django-admin.py compilemessages
Now you can open your django.po file and add your translations to the edited text content in your templates. If your venv folder ins't in your root folder. You can just run django-admin.py makemessages -l fr instead.
If you don't do this, you will end up doing things manually in your .po file. You don't wanna do that.
I hope this helped.
I've created a ticket for this at http://code.djangoproject.com/ticket/15980.
It appears to be a simple typo in the Django code, the problem being that python treats "utf8" as an alias for "utf-8", but xgettext does not. The problem still exists as of Django r16169 (05/06/11 12:49:06) in SVN.
EDIT: The issue has been fixed now in the Django source (as of May 2011).
Recently, I had the same issue, and I couldn't find a fitting solution online. After a few tries, I resolved the error in my case. While creating the trans tags, make sure you do this for each paragraph excluding the paragraph breaks.
Instead of:
<p>
{% trans "
Paragraph I
Paragraph II
" %}
</p>
This may solve the error:
<p>
{% trans "Paragraph I" %}
</p>
<p>
{% trans "Paragraph II" %}
</p>
Related
I am trying to use bootstrap_datepicker_plus and to do that I need bootstrap4. I have installed it. when I run pipenv run pip freeze, I see:
django-bootstrap==0.2.4
django-bootstrap-datepicker-plus==3.0.5
django-bootstrap4==2.3.1
django-compressor==2.4
django-jquery==3.1.0
and I have in settings.py:
INSTALLED_APPS = [
"bootstrap4",
"bootstrap_datepicker_plus",
But I still see
TemplateSyntaxError at /myapp/
'bootstrap4' is not a registered tag library. Must be one of:
when I include {% load bootstrap4 %} in my template.
Does anyone have an idea of why the tag is not registered? I have restarted the server.
Django allows you to use different settings for different environments. My project was using this but left the settings.py file there which was not being used. There was a base.py file in the settings folder that I should have been editing.
I am trying to translate a string.
{% load i18n %}
{% trans "Well, Hello there, how are you?" %}
to...
Hola amigo, ¿que tal?
My settings.py file has this:
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'translations'),
)
And I am getting this:
(env)glitch:translations nathann$ django-admin.py compilemessages
CommandError: Can't find msgfmt. Make sure you have GNU gettext tools 0.15 or newer installed.
I also don't understand this error message.
(env)glitch:ipals nathann$ django-admin.py makemessages -l es
CommandError:
This script should be run from the Django Git tree or your project or
app tree. If you did indeed run it from the Git checkout or your project
or application, maybe you are just missing the conf / locale(in the
django tree) or locale(for project and application) directory? It is not
created automatically, you have to create it by hand if you want to
enable i18n for your project or application.
The docs: https://docs.djangoproject.com/en/1.6/ref/django-admin/#django-admin-makemessages
And for bonus upvotes, a related question:
gettext wasn't linked when I installed it... Any help with this one? Should I force it?
glitch:translations nathann$ brew link gettext
Warning: gettext is keg-only and must be linked with --force
Note that doing so can interfere with building software.
Thanks!
UPDATES:
I have since changed the name of translations to locale and updated my settings.py accordingly. then I ran this again and it's still complaining about gettext:
(env)glitch:ipals nathann$ mv translations/ locale
(env)glitch:ipals nathann$ django-admin.py makemessages -l es
CommandError: Can't find xgettext. Make sure you have GNU gettext tools 0.15 or newer installed.
I also found this:
Understand homebrew and keg-only dependencies
after reading this:
(env)glitch:ipals nathann$ brew install gettext
Warning: gettext-0.18.3.2 already installed
(env)glitch:ipals nathann$ brew link gettext
Warning: gettext is keg-only and must be linked with --force
Note that doing so can interfere with building software.
After making sure I had this in settings:
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
print(LOCALE_PATHS)
I double checked I had the locale directory in the right place with its name spelled correctly.
I ended up linking gettext (after asking about that on superuser):
brew link gettext --force
manage.py compilemessages
django-admin.py makemessages -l es
And BAM. I've got my po file.
But the doctor says:
Warning: Some keg-only formula are linked into the Cellar.
Linking a keg-only formula, such as gettext, into the cellar with
`brew link <formula>` will cause other formulae to detect them during
the `./configure` step. This may cause problems when compiling those
other formulae.
Binaries provided by keg-only formulae may override system binaries
with other strange results.
You may wish to `brew unlink` these brews:
gettext
Please try this in Ubuntu
sudo apt-get install gettext
And use brew install gettext in OSX
Also make sure to set the local path in settings.py file.
Here is the solution for those having problems with translations or are creating a multi-language site for the very first time in Django. Here is the way I do it, and I have been doing since Django 1.4, below is tested in 1.7.1:
In settings.py …
Add to MIDDLEWEAR_CLASSES, locale, it enables language selection based on request:
'django.middleware.locale.LocaleMiddleware',
Add LOCALE_PATHS, this is where your translation files will be stored, also enable i18N:
USE_I18N = True
LOCALE_PATHS = (
os.path.join(PROJECT_PATH, 'locale/'),
)
Set LANGUAGES that you will be translating the site to:
ugettext = lambda s: s
LANGUAGES = (
('en', ugettext('English')),
('fr', ugettext('French')),
('pl', ugettext('Polish')),
)
Add i18n template context processor, requests will now include LANGUAGES and LANGUAGE_CODE:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n', # this one
'django.core.context_processors.request',
'django.core.context_processors.static',
'django.contrib.messages.context_processors.messages',
)
Nest, in urls.py :
In url_patterns, add the below, it will enable the set language redirect view:
url(r'^i18n/', include('django.conf.urls.i18n')),
See Miscellaneous in Translations for more on this.
Add the following imports, and encapsulate the urls you want translated with i18n_patterns. Here is what mine looks like:
from django.conf.urls.i18n import i18n_patterns
from django.utils.translation import ugettext_lazy as _
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^i18n/', include('django.conf.urls.i18n')),
)
urlpatterns += i18n_patterns('',
(_(r'^dual-lang/'), include('duallang.urls')),
(r'^', include('home.urls')),
)
Note: You can also drop your admin urls into the i18n_patterns.
Now anywhere you use text and want to convert it, import lazytext and wrap every string with it like so _('text'), you can even go to your other urls.py files and do url translation like so:
url(_(r'^dual_language/$'), landing, name='duallang_landing'),
You can wrap text that you want translated in your other files, such as models.py, views.py etc.. Here is an example model field with translations for label and help_text:
name = models.CharField(_('name'), max_length=255, unique=True, help_text=_("Name of the FAQ Topic"))
Django translation docs are great for this!
In your html templates...
Now you can go into your templates and load the i18n templatetag and use trans and transblock on the static stuff you want to translate. Here is an example:
{% load i18n %}
{% trans "This is a translation" %}<br><br>
{% blocktrans with book_t='book title'|title author_t='an author'|title %}
This is {{ book_t }} by {{ author_t }}. Block trans is powerful!
{% endblocktrans %}
Now run a makemessages for each of your locales:
./manage.py makemessages -l pl
And now all is left is to go into your /locales folder, and edit each of the .po files. Fill in the data for each msgstr. Here is one such example of that:
msgid "English"
msgstr "Angielski"
And finally compile the messages:
./manage.py compilemessages
There is a lot more to learn with translations and internationalization is closely related to this topic, so check out the docs for it too. I also recommend checking out some of the internationalization packages available for Django like django-rosetta, and django-linguo. They help translate model content, django-rosetta does not create new entries for this in your database, while django-linguo does.
If you followed this you should be off to a good start. I believe this is the most standardized way to get your site running in multiple languages. Cheers!
For Mac users brew link gettext --force can be risk, as Brew advises. A better work around is to set a new PATH variable for your virtual environment. So, in the postactivate file, which is located in the bin folder of your virtual environment folder, type:
export TEMP_PATH=$PATH
export PATH=$PATH:/usr/local/Cellar/gettext/0.19.7/bin
Note that you have to replace 0.19.7 by the version that is installed in your machine.
And in your predeactivate file, which is located in the same folder of postactivate file, type:
export PATH=$TEMP_PATH
unset TEMP_PATH
Now you can use the python manage.py makemessages -l <desired_language> without worries. :)
Cheers.
For macOS :
brew install gettext
export PATH="/usr/local/opt/gettext/bin:$PATH"
Have you added {% load i18n %} to the top of your template?
Bonus: You don't need to link gettext, what is the output from brew doctor?
Please install gettext in your ubuntu OS
using sudo apt-get command
Or in Mac
using brew command
If you don't want to link gettext (which you shouldn't because messing about with OS X internals is bad) then you can set the PATH for the makemessages command. The following should work (but you need to adjust your gettext version number):
PATH=/usr/local/Cellar/gettext/<installed version>/bin/:$PATH && \
django-admin makemessages -l <language>
If you do it that way your installed gettext remains keg-only and django-admin will be happy and find all the programms it needs.
One of the possibilities is that after you have successfully done all the above and done
pip install python-gettext
you may have improperly configured your IDE or venv. In order to bypass this, go to the command prompt, navigate to your root folder and run py manage.py makemessages from there. It will work.
For me, on Windows 10, the problem was that I used gettext installed with pip install (I got version 0.19-something). I made it work by:
Uninstalling gettext with pip.
downloading gettext (as a zip) from here istead: https://mlocati.github.io/articles/gettext-iconv-windows.html
Extracting the files in a foler on "C:/program files"
Added the path to the "bin" folder (inside the extracted folder) to PATH in my environment variables in windows.
After that it worked! (after 5 h frustrated debugging...)
I finished a few days ago, creating a translation file for Django-LFS (Lightning Fast Shop) for my native language (pt_BR). Now that it's done, I need to install the ".po" file that I downloaded after finishing my translation in Transifex.
Ok, I downloaded the file, but now that I need to install it, I just can't figure how. I tried putting the file in 'lfs-installer' folder, using "bin/django compilemessages -a", tried the same thing but with the file in many different folders, but I just can't make my LFS use my translation file...
Does anyone know how to make a translation package work on lfs? Or am I doing something wrong?
Thanks
put you .po file in the path:
<your_django_project>/conf/locale/pt_BR/LC_MESSAGES/
and run
django-admin makemessages -a
If you do not already have one, create a folder called Locale. Then in your settings.py folder you must tell it where to find the locale paths. Something like this:
LOCALE_PATHS{
C:/sdalfjasd/dfalsdjkf/locale
}
Also make sure you have locale middleware in your middleware...
You can probably effectively track down that syntax and specifics, now that I pointed you in the right direction.
Once you have those things set up, you can run your makemessage -a command, which will create a folder in your locale folder for the -a you put in. Then you can browse to this, inside it there should be a .po file (there might not be). If there is not, just put your .po file you made in there.
Then browse to your project in your CMD, and run compilemessages -a. This should compile your .po files into .mo files, the files necessary for translations to work.
Hopefully I did not go crazy off-track...
I made it to work using the following settings:
import os
DIRNAME = os.path.dirname(__file__)
USE_I18N = True
USE_L10N = True
LANGUAGE_CODE = 'pt-br'
LANGUAGES = (
('pt-br', u"Português"),
)
LOCALE_PATHS = [
DIRNAME + '/locale',
]
Than create a locale folder aside of the settings.py folder and follow Django official instructions. The desired path for your django.po file is: locale/pt_BR/LC_MESSAGES/django.po. After that, use compilemessages tool and restart the server.
It should work.
Tip: django-lfs uses locale module to handle currency display, but there is a bug for locale module that makes it to show 1234,00 R$ instead of R$ 1234,00. If it bites you, put the following into your settings.py:
# Fix for LC_MONETARY bug: http://www.sourceware.org/bugzilla/show_bug.cgi?id=1294
import locale
locale._override_localeconv.update({'p_cs_precedes': 1, 'n_cs_precedes': 1})
Good luck.
Im trying to learn Django by looking at examples, but Im having a bit of a problem running the examples I find.
I downloaded 'cheeserator' from https://github.com/jacobian/cheeserater
and I tried running it with python manage.py runserver
but I get the following error -
Error: Can't find the file
'settings.py' in the directory
containing 'manage.py'. It appears
you've customized things. You'll have
to run django-admin.py, passing it
your settings module. (If the file
settings.py does indeed exist, it's
causing an ImportError somehow.)
What am I doing wrong?
You need to have a settings.py file.
As per the instructions in the link provided:
Then you'll want to create a settings.py file in this directory containing::
from settings_template import *
# Override any settings you like here.
Or if you don't want to override anything rename settings_template.py to settings.py
I have a small Django project I received from a friend. The code works perfectly on his system. However, on my system I get the following error message when running the server:
TemplateSyntaxError at /
'current_tags' is not a valid tag library: Template library current_tags not found, tried django.templatetags.current_tags
The problem is with a line in an html file:
{% load current_tags %}
This exact same code works on his system with no errors. What could that be?
I would suggest the following:
(Most likely) You haven't installed one of the dependencies of your tag library. Check the imports inside the current_tags.py module.
Make sure the application that includes the tag library is registered in settings.py under INSTALLED_APPS.
Make sure that you can successfully import the tag library.
python manage.py shell
>>> from app.templatetags import current_tags
This boils down what the following link recommends, which is that the error itself tends to mislead you about where it's looking for a template from. It silently ignores errors on import, which means current_tags.py itself might have a syntax error or another reason why it raises ImportError.
If everything else fails, check this link:
http://www.b-list.org/weblog/2007/dec/04/magic-tags/
I had this problem and fixed it by adding a blank __init__.py file in my appname/templatetags/ directory.
Possibilities are many:
You haven't reset your dev server.
You have dependency loop in templatetag file.
You misspelled something (directory, folder, template name in 'load', etc.).
You forgot about adding the app to INSTALLED_APPS.
Restart the server has solved the issue for me. They must have mentioned it in the documentation.
I was getting the same error but for a different reason so I'll tell you (in case someone else comes the same problem).
I had everything right but I had my custom tag inside a folder named template_tags and after a long search I found out that it had to be templatetags, and now it works. So check the folder name is exactly templatetags.
suppose you have the following structure:
-- Application_Name
-------templatetags
--------------init.py
--------------templates_extras.py
-------init.py
-------settings.py
-- manage.py
You have to make sure of the following:
your application itself inside which your "templatetags" is resident is actually installed in INSTALLED_APPS in settings.py (e.g. "Application_Name")
your tag module itself that exists inside "templatetags" is already installed in INSTALLED_APP in settings.py (e.g. "ApplicationName.templatetags.tempaltes_extras")
keep sure you have "init.py" under templatetags directory
you have to restart the server
In some cases you have to remove all generated *.pyc if it did not work then retry again
"custom tags" is not a valid tag library error, more often is occurred because the custom tags are not loaded into the app.
place an empty init.py inside the same folder where your "custom template tag" is placed and run the below code on the terminal to load the custom template tags
touch __init__.py
For others facing this . Suppose your App name is MyApp and your tag folder name is templatetags then in settings.py you should have :
INSTALLED_APPS = [
'MyApp',
'MyApp.templatetags'
]
Both your django app and your tag folder which is under your app package are needed there.
-> MyApp
---> models.py
---> views.py
---> templatetags
-----> __init__.py
-----> app_filters.py
And in your template file :
{% load app_filters %}
Also app_filters.py be like :
# coding=utf-8
from django import template
register = template.Library()
#register.filter(name='get_item')
def get_item(dictionary, key):
return dictionary.get(key)
check all above steps and you may find the issue.
Please ensure your templatetags folder is initialized with python, if you are in doubt, just take bakup of all files,
Remove all files,
Inside templatetags folder create init.py file only,
then restart your server,
Now your folder is under Python, then do your stuff.
This works for me...
For me, it was the mistake of putting quotes around the library name in load tag.
WRONG: {% load 'library_name' %}
CORRECT: {% load library_name %}
Refer to other answers too. I solved a couple of those problems too before landing here.
Make sure the load statement is correct. It should be the name of the file, not the name of the app. For instance, if you have this app:
appname
├── __init__.py
├── templatetags
│ ├── __init__.py
│ └── foobarfilename.py
Then you should put this in your template:
{% load foobarfilename %}
Of course, you should check the other answers too.
After you have created the template tag and it should be within the 'templatetags' package within an app installed in the settings.INSTALLED_APPS, make sure you restart your dev-server.
Maybe someone will find this useful: somehow I had named the directory 'templatetags ' instead of 'templatetags', that is -- with a space at the end. Took hours to finally realize.
All of the advice listed here didn't help me. So in my specific case the problem was that the templatetag had to be loaded from a third-party app, and I manually copied source folder with that app into src folder in my virtualenv. Then I ran python setup.py install inside that folder. After that django could not load this module.
Then I removed the source and installed folder of this app and installed it using pip install -r requirements.txt after adding a relevant line into requirements.txt file. It was downloaded into the src folder, installed and everything began working properly. Hope this helps someone.
In my case
I have created library instance using tag variable instead of register variable
tag = template.Library()
But it should be
register = template.Library()
To be a valid tag library, the module must contain a module-level
variable named register that is a template.Library instance, in which
all the tags and filters are registered
In my case the problem was,
I was using {% load filter_method_name %}
I had to change to {% filename %}
In my case it was - I am using
#register.inclusion_tag('template-to-use.html')
I forgot to create that template and right away it started working. I know above answers are more related to most of the issues - but hope maybe someone find it useful. It should have gotten to me:
Template does not exist
but it did not and this worked.