Django translations not working? - django

I want to translate my website to other language , i've configured my settings.py as it should be but no changes are happens.
I've created messages and i can see them inside my local folder, also i've compiled them successfully without any erors.
Here is my settings :
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# My apps
'main',
# Third part apps
'captcha',
'jsonify'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
LOCAL_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
LANGUAGE_CODE = 'en'
LANGUAGES = (
('ru', _(u'RU')),
('en', _(u'EN'))
)
My views:
from django.utils.translation import gettext as _
def main(request):
context = {
'title':_('Главная'),
}
return render(request, 'index.html', context)
Also i've loaded the i18n above inside my template where the translations happens index.html:
{% load static %}
{% load i18n %}
<title>{% block head_title %}{{title}}{% endblock %}</title>

I got it to work, instead of typing LOCALE_PATHS i typed LOCAL_PATHS, now everything is working just fine .

Related

django-allauth-2fa: Unexpected behaviour of accounts/two_factor/setup/ -> page reload after pressing 'verify'

I am trying to use django-allauth & django-allauth-2fa in my Django app.
My django-allauth app is set uo correctly - everything is working as expected.
However, when trying to set up django-allauth-2fa I ran into some issues: Configuring a two-factor authentification at accounts/two_factor/setup/ when I scan the QR code, input the token generated and press verify the page simply reloads with a new QR code instead of leading me to the next step in the Two-Factor configuration workflow. I can't figure out what my mistake may be, as I set up everything as written in the django-allauth-2fa documentation
My Pipfile:
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[dev-packages]
[packages]
django = "==3.0.0"
pylint = "==2.4.4"
django-crispy-forms = "==1.9"
django-allauth = "==0.42.0"
django-allauth-2fa = "==0.8"
[requires]
python_version = "3.7"
my settings.py file:
...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
# Local
'users.apps.UsersConfig',
'pages.apps.PagesConfig',
#Third-party
'allauth',
'allauth.account',
'django_otp',
'django_otp.plugins.otp_totp',
'django_otp.plugins.otp_static',
'allauth_2fa',
'crispy_forms',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django_otp.middleware.OTPMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'allauth_2fa.middleware.AllauthTwoFactorMiddleware',
]
SITE_ID = 1
ACCOUNT_ADAPTER = 'allauth_2fa.adapter.OTPAdapter'
...
my urls.py file:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('allauth_2fa.urls')),
path('accounts/', include('allauth.urls')),
path('', include('pages.urls')),
]
And I also ran python manage.py migrate
had the same problem on Ubuntu20 . Fix it with enbaling automatic sync date & times.

Django messages framework - lack of i18n by default

By default django messages framework does not localize it's messages correctly.
For example in admin interface
As you can see all other things in admin panel are localized. The translation file exists. Here is my settings.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
...
]
MIDDLEWARE = [
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.locale.LocaleMiddleware',
]
LANGUAGE_CODE = 'ru' # I've tried 'ru-RU'
TIME_ZONE = 'Europe/Moscow'
USE_I18N = True
USE_L10N = True
USE_TZ = True
How to fix this? Thanks in advance. I have django version 3.0.6. This error also is absent in django 1.8
It was a breaking change from django/django#42b9a23 (Django 3.0+) that only updated the French translations.
You can patch DjangoTranslation.gettext to handle the smart quotes.
def _patch_gettext():
from django.utils.translation.trans_real import DjangoTranslation
_gettext = DjangoTranslation.gettext
def gettext(self, message):
text = _gettext(self, message)
if text is message and '“' in message:
new_message = message.replace('“', '"').replace('”', '"')
new_text = _gettext(self, new_message)
if new_text is not new_message:
return new_text
return text
DjangoTranslation.gettext = gettext
About patching
Subclass AppConfig in mysite/apps.py:
from django.apps import AppConfig
class MySiteAppConfig(AppConfig):
name = 'mysite'
def ready(self):
_patch_gettext()
Put the dotted path to that subclass in INSTALLED_APPS in mysite/settings.py:
INSTALLED_APPS = [
...
'mysite.apps.MySiteAppConfig',
]
Reference: https://docs.djangoproject.com/en/3.0/ref/applications/#configuring-applications

How to redirect page to user with user prefered language when opening a browser

Django 1.9.6 i18n works perfect when I open the browser and change language.
But I want to save language and the other times when user comes it will be in his/her prefered language.
Now when I open the site it always redirect me to /en .I tried to change my settings and set
LANGUAGE_CODE='ru'
or something else but it does not work here is my settings file
ALLOWED_HOSTS = []
LOGIN_URL=reverse_lazy('login')
AUTH_USER_MODEL='custom.MyUser'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'custom',
'languages',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'builtcustom.urls'
WSGI_APPLICATION = 'builtcustom.wsgi.application'
LANGUAGES=(
('en',_('ENGLISH')),
('fr',_('FRENCH')),
('cs', _('czech')),
('hy', _('ARMENIAN')),
('ru', _('RUSSIAN')),
)
LOCALE_PATHS = (
os.path.join(BASE_DIR, 'locale'),
)
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ =False
How can i solve this problem and redirect to url with a language that I want(Dynamically selected from database)??
For a particular url you an select language like this in Django.
from django.utils.translation import activate
activate('fr') # To use french
Checkout the documentation.
You can easily get whatever language you want from the database and call activate on it. Make sure your the languages in database has same abbreviations as in Django.

Django admin page: type object 'CommonMiddleware' has no attribute 'is_usable'

I am looking into Django for a database-heavy web application. I started by following the basic tutorial, then added a MySQL database and created a folder for models, views and tests. (I deleted the old models.py, tests.py, views.py.) I can create new models and sync them with my database.
Everything seemed to work until I decided to try the Django admin interface. I am getting an error that does not explain itself very well:
AttributeError at /admin/
type object 'CommonMiddleware' has no attribute 'is_usable'
I have no idea what is causing this. This is my urls.py:
urlpatterns = patterns(
'',
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
And here is my settings.py, stripped of comments:
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('admin', 'admin#example.com'),
)
MANAGERS = ADMINS
DATABASES = dict(
default=dict(
ENGINE='django.db.backends.mysql',
NAME='mydbname',
USER='root',
PASSWORD='******',
HOST='',
PORT='8000',
)
)
# This is redirected to localhost by C:Windows/System32/drivers/etc/hosts
ALLOWED_HOSTS = ['mysite.com']
TIME_ZONE = 'Europe/Amsterdam'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
USE_TZ = True
MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = ( )
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
SECRET_KEY = '****************************************'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'bandage.urls'
WSGI_APPLICATION = 'bandage.wsgi.application'
import os
TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\', '/'),)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'application',
)
As you can see, I have enabled the admin site and it finds the URL, yet I get some error in a module that is part of the Django library. Here is the full trace:
Environment:
Request Method: GET
Request URL: http://mysite.com/admin/
Django Version: 1.5.1
Python Version: 2.7.0
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "D:\Python27\lib\site-packages\django-1.5.1-py2.7.egg\django\core\handlers\base.py" in get_response
140. response = response.render()
File "D:\Python27\lib\site-packages\django-1.5.1-py2.7.egg\django\template\response.py" in render
105. self.content = self.rendered_content
File "D:\Python27\lib\site-packages\django-1.5.1-py2.7.egg\django\template\response.py" in rendered_content
80. template = self.resolve_template(self.template_name)
File "D:\Python27\lib\site-packages\django-1.5.1-py2.7.egg\django\template\response.py" in resolve_template
58. return loader.get_template(template)
File "D:\Python27\lib\site-packages\django-1.5.1-py2.7.egg\django\template\loader.py" in get_template
146. template, origin = find_template(template_name)
File "D:\Python27\lib\site-packages\django-1.5.1-py2.7.egg\django\template\loader.py" in find_template
129. loader = find_template_loader(loader_name)
File "D:\Python27\lib\site-packages\django-1.5.1-py2.7.egg\django\template\loader.py" in find_template_loader
112. if not func.is_usable:
Exception Type: AttributeError at /admin/
Exception Value: type object 'CommonMiddleware' has no attribute 'is_usable'
Any help is greatly appreciated!
You have some Middlewares in your TEMPLATE_LOADERS. Remove them.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
) #\
# | it seems that at some point
# | you accidentally removed these
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',
)

Problem with messages framework in Django 1.2

I'm running Django 1.2 beta and trying out the new feature: message framework.
http://docs.djangoproject.com/en/dev/ref/contrib/messages/
Everything seems to work, but when I try to output the messages, I get nothing. Seems that messages variable is empty. I double checked all the settings, they seem to be just like in the manual. What could be wrong?
settings.py
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.messages.middleware.MessageMiddleware', #send messages to users
'django.middleware.locale.LocaleMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
#debug tool
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.messages.context_processors.messages', #send messages to users
'django.core.context_processors.auth',
)
#Store messages in sessions
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage';
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
#'django.contrib.sites',
'django.contrib.admin',
'django.contrib.messages',
'debug_toolbar',
#my apps
#...
)
views.py
def myview(request):
from django.contrib import messages
messages.error(request, 'error test');
messages.success(request, 'success test');
return render_to_response('mytemplate.html', locals());
mytemplate.html
{% for message in messages %}
{{ message }}<br />
{% endfor %}
In template nothing is outputted.
You'll need to use a RequestContext in your call to render_to_response.
return render_to_response('mytemplate.html', locals(),
context_instance=RequestContext(request))
See the note a few screens down under this documentation section.