Django dynamic localization not working as expected on mobile devices - django

I have question about show current language on mobile devices if I populate my language list in template dynamically (got from languages array from settings)...
So, this code working properly:
EN
BUT, when I'm trying this code, I can't achive that active class added to current language:
{% for lng in settings.LANGUAGES %}
{% if not lng.0 == "ru" %}
<a href="#" id="language-{{ lng.0 }}"
class="pure-drawer-link{% if LANGUAGE_CODE == '{{ lng.0 }}' %} active{% endif %}">
{{ lng.0|upper }}
</a>
{% if LANGUAGE_CODE == '{{ lng.0 }}' %} active {% else %} nonactive{% endif %} => this always return nonactive
{% endif %}
{% endfor %}
Can anyone help to understood why this is happening?
EDIT 1:
My middlewars in settings:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'my_app.middleware.ExpirationMiddleware',
'my_app.middleware.IPMiddleware',
'my_app.middleware.TranslationMiddleware',
]
and this for i18:
USE_I18N = True
USE_L10N = False
USE_TZ = True
TIME_ZONE = 'Europe/Zurich'
LANGUAGE_CODE = 'en-US'

Related

Django error: CSRF verification failed only with Apache (not with development server)

I have a simple page where the user can select from some list and pressing the submit button can download a csv file generated on the fly according to the selection.
I am following the examples and tutorials provided by the official Django website (Django version 2.1, Python 3.6)
in mytemplate.htm:
<div>
<form action="{% url 'myurl_to_downloadcsvView' %}" method="post">
{% csrf_token %}
{% for obj in object_list %}
<input type="radio" name="myname" id="choice{{ forloop.counter }}" value="{{ obj.pk }}">
<label for="choice{{ forloop.counter }}"> {{ obj.name }}</label><br>
{% endfor %}
<input type="submit" value="Download">
</form>
</div>
in views.py:
class ListView(ListView):
template_name = 'mytemplate.htm'
model = mymodel
def downloadcsvView(request):
blahblah (something I create on the fly)
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
writer = csv.writer(response)
for r in blahblah:
writer.writerow(r)
return response
in settings.py:
MIDDLEWARE = [
'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',
]
When I test it with the development server (i.e. manage.py runserver), it works, but when I start the Apache server, when pressing the submit button, I get the error: FORBIDDEN (403) 'CSRF verification failed. Request aborted.' Reason given for failure: CSRF cookie not set.
I can "solve" this only by putting #csrf_exempt before the "downloadcsvView".
How can I make it work also with the production server?

Django not translating the site properly

After spending too many hours on this, StackOverflow is for the rescue.
I configured my settings.py as below:
...
TIME_ZONE = 'Europe/Berlin'
LANGUAGE_CODE = 'de'
LANGUAGES = (
('en', u'English'),
('de', u'German'),
('fr', u'French'),
)
USE_I18N = True
USE_L10N = True
MIDDLEWARE_CLASSES = (
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.request',
'django.core.context_processors.static',
'django.contrib.messages.context_processors.messages',
)
...
In my base.html file, I have a form as below:
<form action="/i18n/setlang/" method="post">
{% csrf_token %}
<input name="next" type="hidden" value="/" />
<select name="language">
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<option value="{{ language.code }}">{{ language.name_local }} ({{ language.code }})</option>
{% endfor %}
</select>
<input type="submit" value="Go" />
</form>
My urls.py:
urlpatterns = patterns('',
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^$', 'MainApp.views.index'), #root
)
In the same base.html file, I have on top {% load i18n %} and in the body, I have a sample {% trans "This is the title." %}. Before running the server, I did:
django-admin.py makemessages -l de
django-admin.py makemessages -l fr
The sample text above was picked up by makemessages, and I provided the respective translations for msgstr. After that, I did django-admin.py compilemessages. The command ran nicely and generated the .mo files in the respective locale folders.
I run the server and the the form does not work. From a another StackOverflow post, I was hinted to remove the #, fuzzy lines, which I did. What am I doing wrong?
Thanks!
You should put the LocaleMiddleware after the SessionMiddleware in your MIDDLEWARE_CLASSES:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
....
)
The order of middleware classes is important. The LocaleMiddleware uses session data to detect the user language, so it must come after the SessionMiddleware. It is also mentioned in the docs here https://docs.djangoproject.com/en/1.3/topics/i18n/deployment/#how-django-discovers-language-preference
Let's hope this works for you!

Django translations always rendering in english

After looking at the trying all of the recommendations I could find on this subject, my translations still do not work whatsoever.
/settings.py file
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
LOCALE_PATHS = (
'/Users/samb/Projects/transtest/locale'
)
# Custom Languages
ugettext = lambda s: s
LANGUAGES = (
('de', ugettext('German')),
('en', ugettext('English')),
('fr', ugettext('French')),
('fr-CA', ugettext('French Canadian')),
)
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
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
view.py
from django.shortcuts import render_to_response
from django.template import RequestContext
def trans(request):
return render_to_response('index.html', context_instance=RequestContext(request))
my template file (index.html)
{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
<html>
<head>
<title>translations</title>
</head>
<body>
{% for l in LANGUAGES %}
{{ l }}<br />
{% endfor %}
{{ LANGUAGE_CODE }}<br />
{% trans "Welcome to my site" %}
</body>
</html>
po file (that has been compiled)
located at /Users/samb/Projects/transtest/locale/fr/LC_MESSAGES
#: transtest/templates/index.html:13
msgid "Welcome to my site"
msgstr "Please work"
I can never get the 'Welcome to my site' to work. The LANGUAGES and LANGUAGE_CODE variables in my template are all working (unless I 'Accept_language: fr_CA').
After reading all the other posts on this subject and still having the same problem, I feel like I must have a silly mistake, or am missing a vital step entirely. Any thoughts?
Update: This is how I am testing the translation:
telnet localhost 8000
Connected to localhost.
Escape character is '^]'.
GET /
Accept_language: fr
<html>
<head>
<title>Translations</title>
</head>
<body>
('de', u'Allemand')<br />
('en', u'Anglais')<br />
('fr', u'Fran\xe7ais')<br />
('fr-CA', u'French Canadian')<br />
fr<br />
Welcome to my site
</body>
</html>
Connection closed by foreign host.
I noticed that the languages are getting translated, but the 'Welcome to my site' is not.
The docs say here that LocaleMiddleware ...
... should come after SessionMiddleware, because LocaleMiddleware makes
use of session data. And it should come before CommonMiddleware
because CommonMiddleware needs an activated language in order to
resolve the requested URL.
Maybe it will help when you take account of this in your definition of the MIDDLEWARE_CLASSES.

request is missing from context

I'm trying to use django-localeurl in one of my project, but following the docs I just get an Error. What I want, is make work this code in the template:
{% load i18n %}
{% load localeurl_tags %}
{% get_available_languages as LANGUAGES %}
{% get_current_language as LANGUAGE_CODE %}
{% for lang in LANGUAGES %}
{% ifequal lang.0 LANGUAGE_CODE %}
<li class="selected">{{ lang.1 }}</li>
{% else %}
<li>{{ lang.1 }}</li>
{% endifequal %}
{% endfor %}
it's from: http://packages.python.org/django-localeurl/usage.html
I got this error
Caught AssertionError while rendering: URL must start with SCRIPT_PREFIX:
The problem is in this line:
<li>{{ lang.1 }}</li>
request.path is an empty string. but why? in the browser I can see 127.0.0.1/hu/, so If I'm right It should contain /hu/.
I created a brand new project just with django 1.3 and django-localeurl in the virtual environment, for simplicity.
My settings.py looks like (the important parts as I know):
LANGUAGES = (
('hu', 'Hungarian'),
('en', 'English'),
('sk', 'Slovakian'),
)
LANGUAGE_CODE = 'hu'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'localeurl.middleware.LocaleURLMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.request",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages",
)
INSTALLED_APPS = (
'localeurl',
'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',
)
What Am I missing?
Edit 1:
I can put the request.path manually to the context:
def main(request):
return render_to_response( 'base.html', {'rpath': request.path})
than I use rpath in the template instead of request.path, but, but.... request.path should contain something, because of django.core.context_processors.request in the TEMPLATE_CONTEXT_PROCESSORS.
The problem was not related to localeurl, with the following view works:
return render_to_response( 'base.html', {}, context_instance = RequestContext(request))
I thought putting django.core.context_processors.request into TEMPLATE_CONTEXT_PROCESSORS do the job, but not.
Locale URL middleware hacks request.path I think what you're looking for is request.path_info
In your view, when returning a response, specify the context_instance like this:
from django.shortcuts import render_to_response
from django.template.context import RequestContext
return render_to_response('base.html',{'object':object},context_instance=RequestContext(request))

django 1.3 internationalization... switching language requires server restart?

I used django 1.2 before and didn't have any problem switching language... In my template i have this...
<form action="/i18n/setlang/" method="post" class="forms">
{% csrf_token %}
<input name="next" type="hidden" value="/next/page/" />
<select name="language" id="select_langauge" class="m_show hide">
{% for lang in LANGUAGES %}
{% if lang.0 != '' %}
<option value="{{lang.0}}">{{lang.1}}</option>
{% endif %}
{% endfor %}
</select>
This was working fine with django 1.2. But since upgraded to Django 1.3 this does not work. I can see that LANGUAGE_CODE changes, but the actual language output is not what I was expecting.
However, when i restart django server, it shows correct language. What am i missing???
I have this in my settings.py
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
gettext = lambda s: s
LANGUAGES = (
('', gettext('Please select')),
('en', gettext('English')),
('ko', gettext('Korean')),
)
USE_L10N = True
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.locale.LocaleMiddleware',
)
I figured out.
To change language dynamically, using ugettext_lazy() fixed the problem. (Before I was using ugettext).
Reference: https://docs.djangoproject.com/en/1.3/topics/i18n/internationalization/#lazy-translation