translation not working in Django 1.5 even after compiling message - django

I'm using Django 1.5
I have to enable internationalization in my application. For that, I have added a few things to the settings.py file
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
...
)
from django.conf import global_settings
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
'...local context processrors...'
)
# global_settings.TEMPLATE_CONTEXT_PROCESSORS contains
# TEMPLATE_CONTEXT_PROCESSORS = (
# 'django.contrib.auth.context_processors.auth',
# 'django.core.context_processors.debug',
# 'django.core.context_processors.i18n',
# ...
# )
USE_I18N = True
USE_L10N = True
LANGUAGE_CODE = 'es'
# List of languages available for translation
ugettext = lambda s: s
LANGUAGES = (
('en', ugettext('English')),
('es', ugettext('Spanish'))
)
LOCALE_PATHS = (
os.path.join(PROJECT_ROOT, 'locale/'),
)
The LOCALE_PATHS has the location output as
('/media/path_to_project/workbench/workbench/settings/../locale/',)
But on running ./manage.py makemessages -l es it generates *.po file in
/media/path_to_project/workbench/workbench
instead of
/media/path_to_project/workbench/workbench/locale
Also, the compiled language is not showing in the template.

You need to check following things.
Ensure that you added USE_L10N = True and USE_I18N = True into your settings.py file
Check for PROJECT_ROOT and LOCALE_PATHS and make sure that it is correct
Add django.core.context_processors.i18n to TEMPLATE_CONTEXT_PROCESSORS in setting.py.
Translation and formatting are controlled by USE_I18N and USE_L10N settings respectively. However, both features involve internationalization and localization. The names of the settings are an unfortunate result of Django’s history.

Related

django admin automatic rtl for some languages

I'm trying to add multi language support for a django project using Django i18n official documentaion:
https://docs.djangoproject.com/en/4.1/topics/i18n/translation/
When I change the LANGUAGE_CODE to something like 'fa', by default the admin panel changes to RTL.
But the problem is when I use other RTL languages like 'ku' (kurdish) the page remains in ltr.
I know we can change the css manualy, but wonder what is the problem here and how some languages like Arabic or persian does the RTL part automaticaly but others dont.
Thanks in advance
# settings.py
LANGUAGE_CODE = 'en-us'
USE_I18N = True
USE_L10N = True
TIME_ZONE = 'UTC'
USE_TZ = True
LANGUAGES = (
('en', _('English')),
('ku', _('Kurdish')),
('fa', _('Persian')),
)
LOCALE_PATHS = [
Path(BASE_DIR, 'django_i18n', 'locale'),
]
# url.py
urlpatterns = i18n_patterns(
path('admin/', admin.site.urls),
) +static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)
just found the answer here:
https://github.com/django/django/blob/main/django/conf/global_settings.py#L158
So all I had to do was add this to setting.py:
LANGUAGES_BIDI = ["ku",]

How to set the default language for all users or browsers

There are two working versions of the translation on the site - Russian and English using i18n. How to make sure that everyone has a website loaded in Russian and then, at the request of the user, he can change it to English?
MIDDLEWARE = [
...
'django.middleware.locale.LocaleMiddleware',
...
]
LANGUAGE_CODE = 'ru'
LANGUAGES = (
('ru', _('Russian')),
('en', _('English')),
)
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
TIME_ZONE = 'Europe/Kiev'
USE_I18N = True
USE_L10N = True
USE_TZ = True

"Django_celery_beat" executes task only once

I am trying to integrate django_celery_beat in project.
When I setup task using django admin panel, entries in database are reflected correctly and when I start project task gets executed successfully. however on every successive attempt of sending task after first execution is rather failed or either message is not sent to broker.
My setup :
django_celery_beat : 1.0.1
celery: 4.0.1
Setting in celeryconfig:
CELERY_ENABLE_UTC = True
BROKER_URL = 'amqp://guest:guest#localhost:5672//'
CELERYBEAT_SCHEDULER = 'django_celery_beat.schedulers.DatabaseScheduler'
settings.py
# -*- coding: utf-8 -*-
import os
import tempfile
import time
from buy import constants as buy_constants
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
# CSRF_COOKIE_SECURE = True
# SESSION_COOKIE_SECURE = True
ADMIN_SITE_ENABLED = False
WAIT_BETWEEN_RATING = 7 # In days
WAIT_BETWEEN_EMAIL_VERIFY = 30 # In minutes
WAIT_BETWEEN_RECOMMENDATIONS = 1 # In minutes
WAIT_BETWEEN_CONNECTION_UPDATE = 60*24*5 # In minutes
SITEMAP_CACHE = 86400
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (('Pooja Shete', 'pooja.shete#gmail.com'),)
MANAGERS = ADMINS
DATABASES = {}
# Hosts/domain names that are valid for this site; required if DEBUG is False
ALLOWED_HOSTS = ['*']
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = '/media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(PROJECT_ROOT, "static"),
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_STORAGE = 'require.storage.OptimizedCachedStaticFilesStorage'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'pipeline.finders.PipelineFinder',
'pipeline.finders.CachedFileFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'c28yui+jyipz5prse%!o^u_e06$!*_daps8b9+km_aa51f=i%='
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django_user_agents.middleware.UserAgentMiddleware',
'django.middleware.security.SecurityMiddleware',
'logs.middleware.ContextMiddleware',
'middleware.locale.LocaleMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
DJANGO_CONTEXT_LOGGING_EXTRACTOR = lambda request: {}
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'PAGINATE_BY': 10
}
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'app.wsgi.application'
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\','/'),
os.path.join(PROJECT_ROOT, 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'django.contrib.sitemaps',
'django.contrib.admin',
'django.contrib.admindocs',
'billing',
'django_user_agents',
'pipeline',
'celery',
'django_celery_beat',
)
SITE_ID = 1
import django.db.models.options as options
options.DEFAULT_NAMES = options.DEFAULT_NAMES + ('db_name',)
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
CELERYBEAT_SCHEDULER = 'django_celery_beat.schedulers.DatabaseScheduler'
TEMPLATE_CONTEXT_PROCESSORS = ('django.core.context_processors.request',"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.tz",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.csrf",
)
PIPELINE_DISABLE_WRAPPER = True
PIPELINE_COMPILERS = (
'pipeline.compilers.sass.SASSCompiler',
)
PIPELINE_YUGLIFY_BINARY = '/usr/local/bin/yuglify'
PIPELINE_JS_COMPRESSOR = 'pipeline.compressors.uglifyjs.UglifyJSCompressor'
PIPELINE_CLOSURE_ARGUMENTS = '--compilation_level=WHITESPACE_ONLY'
PIPELINE_CSS_COMPRESSOR = 'pipeline.compressors.yui.YUICompressor'
CACHES = {}
# Change this value in local_config as per requirement to use dummy paypal
DUMMY_PAYPAL = False
# Initialize cached object
##############################
try:
INITIALIZE_FILE_CACHE
except NameError:
try:
from django.core.cache import get_cache
cache = get_cache('redis_cache')
try:
wp = cache.get('word_parser', None)
except:
wp = None
if not wp:
from bin.cron.wordparser import WordParser
wp = WordParser()
cache.set('word_parser', wp, timeout=None)
except ImportError:
pass
gettext = lambda s: s
LANGUAGES = (
('en', gettext('English')),
('fr', gettext('French')),
('es', gettext('Spanish')),
('ja_JP', gettext('Japanese')),
)
PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))
LOCALE_PATHS = (
os.path.join(PROJECT_PATH, '../locale'),
)
Command used to start celerybeat:
celery beat -A app-S django_celery_beat.schedulers.DatabaseScheduler --loglevel=INFO
command used to start workers :
celery worker -A app--loglevel=INFO
When I start celery I do get exception of :
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/celery/worker/pidbox.py", line 42, in on_message
self.node.handle_message(body, message)
File "/usr/local/lib/python3.4/dist-packages/kombu/pidbox.py", line 129, in handle_message
return self.dispatch(**body)
File "/usr/local/lib/python3.4/dist-packages/kombu/pidbox.py", line 112, in dispatch
ticket=ticket)
File "/usr/local/lib/python3.4/dist-packages/kombu/pidbox.py", line 135, in reply
serializer=self.mailbox.serializer)
File "/usr/local/lib/python3.4/dist-packages/kombu/pidbox.py", line 265, in _publish_reply
**opts
File "/usr/local/lib/python3.4/dist-packages/kombu/messaging.py", line 181, in publish
exchange_name, declare,
File "/usr/local/lib/python3.4/dist-packages/kombu/messaging.py", line 203, in _publish
mandatory=mandatory, immediate=immediate,
File "/usr/local/lib/python3.4/dist-packages/amqp/channel.py", line 1748, in _basic_publish
(0, exchange, routing_key, mandatory, immediate), msg
File "/usr/local/lib/python3.4/dist-packages/amqp/abstract_channel.py", line 64, in send_method
conn.frame_writer(1, self.channel_id, sig, args, content)
File "/usr/local/lib/python3.4/dist-packages/amqp/method_framing.py", line 174, in write_frame
write(view[:offset])
File "/usr/local/lib/python3.4/dist-packages/amqp/transport.py", line 269, in write
self._write(s)
BrokenPipeError: [Errno 32] Broken pipe
Logs in beat.stderr.log:
[2017-06-12 05:40:00,002: INFO/MainProcess] Scheduler: Sending due task pooja_task (app.tasks.send_test_mail)
[2017-06-12 05:41:00,002: INFO/MainProcess] Scheduler: Sending due task pooja_task (app.tasks.send_test_mail)
[2017-06-12 05:41:00,002: INFO/MainProcess] Scheduler: Sending due task pooja_task (app.tasks.send_test_mail)
However from all above task sent, celery picks only first task and execute whenever I start by server. All other messages are avoided.
Can anyone please help me with this.

Django internationalization not working

My django is not executing translations that i define in my *.po files.
I have my setup like this:
MainFolder:
locale
en
LC_MESSAGES
django.po
django.mo
de
LC_MESSAGES
django.po
django.mo
app1
settings.py
app2
....
in my settings.py i have everything enabled i think:
USE_I18N = True
USE_L10N = True
LANGUAGE_CODE = 'en'
LANGUAGES = (
('en', _('English')),
('de', _('German')),
)
TEMPLATE_CONTEXT_PROCESSORS = (
....
'django.core.context_processors.static',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
)
let's say my django.po file contains an example like this:
msgid "Home"
msgstr "Home22222"
and i use this in my template file:
{% trans "Home" %}
The home is not being replace by Home22222
It stays the same, even when i remove the LocaleMiddleware.
i did ran
makemessages --locale=en
and afterwards:
compilemessages
I am using Python 2.7 and django 1.6.4

Plugin Context Processors in django-cms

I'm trying to get django cms' plugin context processors for my hooked app. I followed the documentation http://docs.django-cms.org/en/2.1.3/extending_cms/custom_plugins.html#plugin-context-processors , but for some reason it doesn't work. Here is a my sample context processor:
def test_context_processor(instance, placeholder):
print instance
return {'testkey':'testvalue'}
and my template:
{% load cms_tags %}
<!doctype html>
<head>
<title></title>
{% plugins_media %}
</head>
<body>
{% placeholder "main" %}
</body>
</html>
I added a text plugin in the main placeholder, and added the text {{testkey}}. It renders it as {{testkey}} instead of testvalue. The print statement in the context processor gets logged properly - meaning that the context processor is called for sure. I'm not sure what am I doing wrong here.
--- Edit ---
My settings file:
# -*- coding: utf-8 -*-
import os
gettext = lambda s: s
PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#domain.com'),
)
MANAGERS = ADMINS
LANGUAGES = [('en', 'en')]
DEFAULT_LANGUAGE = 0
#DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(PROJECT_DIR, 'mycms.db'),
# }
#}
DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = '***' # Or path to database file if using sqlite3.
DATABASE_USER = '***' # Not used with sqlite3.
DATABASE_PASSWORD = '***' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '5432' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/media/'
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/admin/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '0r6%7gip5tmez*vygfv+u14h#4lbt^8e2^26o#5_f_#b7%cm)u'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'cms.middleware.page.CurrentPageMiddleware',
'cms.middleware.user.CurrentUserMiddleware',
'cms.middleware.toolbar.ToolbarMiddleware',
'cms.middleware.media.PlaceholderMediaMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth',
'django.core.context_processors.i18n',
'django.core.context_processors.request',
'django.core.context_processors.media',
'cms.context_processors.media',
)
CMS_PLUGIN_CONTEXT_PROCESSORS = (
'helpdocs.cms_context_processors.test_context_processor',
)
CMS_TEMPLATES = (
('example.html', 'Example Template'),
)
ROOT_URLCONF = 'urls'
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'cms',
'menus',
'mptt',
'appmedia',
'south',
'cms.plugins.text',
'cms.plugins.picture',
'cms.plugins.link',
'cms.plugins.file',
'cms.plugins.snippet',
'cms.plugins.googlemap',
'helpdocs',
)
The Plugin Context Processors are used to process the context with which the templates of the plugin are rendered. They do not alter the content of any database field (in your case, 'body' on the Text model).
Therefore it will not replace anything in your text plugin. To do what you're trying to do, have a look at Plugin Processors (http://docs.django-cms.org/en/2.1.3/extending_cms/custom_plugins.html#plugin-processors) which allow you to process the rendered output of a plugin.
To achieve what you're trying to do you would do something like this:
def my_plugin_processor(instance, placeholder, rendered_content, original_context):
return rendered_content.replace('{{ testkey }}', 'testvalue')