26👍
After more testing and thanks to the related question linked by @AronYsidoro I’ve finally found the issue and a very simple solution that actually solves this.
First, let me explain the problem: When working with i18_patterns
in your urls.py
to prepend the language code, if you call the URL set_language
to change the language without specifying next
, it defaults to the current one, but with the prepended old language code! So, the language gets back to the original! And, if you explicitly specify next
, you must be sure to do not include the language code at the begining.
If you use {{ request.path }}
or {{ request.get_full_path }}
to specify the next
as the current page this won’t work as it returns the language code too.
So, how do we remove this undesired language code to reload the current page with the language changed when using i18n_patterns
? Easy, we just have to slice the 3 first chars (the slash and the two chars language code)!
Here you have two examples. The first one in form of a select (with the languages as choices) and the other one in form of a button (per language).
I really hope this helps someone else. You can just copy and paste the code and it should work. However, if using the "button form", you just have to set the language to your desired!
Change language from list:
<form action="{% url 'set_language' %}" method="post">
{% csrf_token %}
<input name="next" type="hidden" value="{{ request.get_full_path|slice:'3:' }}" />
<select name="language">
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}>
{{ language.name_local }} ({{ language.code }})
</option>
{% endfor %}
</select>
<input type="submit" value="Change" />
</form>
Change language as button:
<form action="{% url 'set_language' %}" method="post">
{% csrf_token %}
<input name="next" type="hidden" value="{{ request.get_full_path|slice:'3:' }}" />
<input name="language" type="hidden" value="es" />
<input type="submit" value="ES" />
</form>
Edit:
Some languages code are larger than 2 characters (like zh-hans, zh-hant), therefore, do something like:
{% if get_current_language == 'zh-hans' or get_current_language == 'zh-hant' %}
<li><a href="/{{ language.code }}{{ request.get_full_path|slice:'8:' }}">{{ language.name_local }} ({{ language.code }}) <b>{% if language.code == get_current_language %} ✓ {% endif %}</b></a></li>
{% else %}
<li><a href="/{{ language.code }}{{ request.get_full_path|slice:'3:' }}">{{ language.name_local }} ({{ language.code }}) <b>{% if language.code == get_current_language %} ✓ {% endif %}</b></a></li>
{% endif %}
21👍
A sum-up of possible options:
Change the user’s session language with a select
There is an excellent extensive description with example on Django docs.
Change the user’s session language with buttons
There is no need to repeat a form for each button as @Caumons suggested, instead you can simply include as many buttons in the form as the languages.
<form action="{% url 'set_language' %}" method="post">
{% csrf_token %}
<input name="next" type="hidden" value="{{ request.get_full_path|slice:'3:' }}" />
<ul class="nav navbar-nav navbar-right language menu">
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<li>
<button type="submit"
name="language"
value="{{ language.code }}"
class="{% if language.code == LANGUAGE_CODE %}selected{% endif %}">
{{ language.name_local }}
</button>
</li>
{% endfor %}
</ul>
</form>
You can certainly style up the buttons to look like links or whatever.
Change the language displayed with links
If it is not required that the default user session language is changed, then simple links can be used to change the content:
<ul class="nav navbar-nav navbar-right language menu">
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<li>
<a href="/{{ language.code }}{{ request.get_full_path|slice:'3:' }}"
class="{% if language.code == LANGUAGE_CODE %}selected{% endif %}"
lang="{{ language.code }}">
{{ language.name_local }}
</a>
</li>
{% endfor %}
</ul>
SEO
I am not entirely sure that the content is seo friendly if a form is used to change the session language, as Django recommends. Therefore it is possible that the link <a>
markup is added as hidden below the <button>
element.
2👍
If in your current system you have only 2 languages then simply use like below:
{% ifequal LANGUAGE_CODE "en" %}
<a href="/es{{ request.get_full_path }}">Spanish</a>
{% else %}
<a href="/en{{ request.get_full_path }}">English</a>
{% endifequal %}
No need of a form, url and submit etc. It worked for me.
2👍
Besides adding form that was suggested here:
<form action="{% url 'set_language' %}" method="post">
{% csrf_token %}
{{ request.get_full_path_info|slice:'3:'}}
<input name="next" type="hidden" value="{{ languageless_url }}" />
<ul class="nav navbar-nav navbar-right language menu">
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<li>
<button type="submit" name="language" value="{{ language.code }}"
class="{% if language.code == LANGUAGE_CODE %}selected{% endif %}">
{{ language.code }}
</button>
</li>
{% endfor %}
</ul>
</form>
I would suggest adding a context processor (app.context_processors.py):
def language_processor(request):
"""
This is needed for language picker to work
"""
return {
'languageless_url':
'/' + '/'.join(request.get_full_path().split('/')[2:])
}
This allows to leave the logic out of template.
Also don’t forget to add your processor in template settings:
'context_processors': [
'app.context_processors.language_processor',
- Django: Faking a field in the admin interface?
- Adding prefix path to static files in Angular using angular-cli
2👍
If you only need two languages, ex. English and French and you’ve defined this in your settings.py and you have set the default language and you have configured urls.py in your main app correctly. Then, just use this in your template (or partial, topbar etc.) btn-kinito "btn-header
are just styling classes you can manipulate that with css or JS.
The loop or iteration inside is just looping through the LANGUAGES[]
list, which you’ve defined in settings.py
, then it creates a button. with the character “|” and a space
to make it look cute since we have just two langs.
The {% url 'set_language' %}
is Django’s redirect view called set_language it redirects to URL. This is why in your main apps’s urls.py you need to put path('i18n/', include('django.conf.urls.i18n')),
In this case. So after the button is created for each language in the list you will be able to be redirected to that url.
<div class="btn-header">
<form action="{% url 'set_language' %}" method="post">
{% csrf_token %}
<input name="next" type="hidden" value="{{ redirect_to }}" />
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<button type="submit" name="language" value="{{ language.code }}"
class="btn-kinito">
{{ language.code }}
</button>|
{% endfor %}
</form>
</div>
For urls.py I think it could look like this:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls.i18n import i18n_patterns
# I don't want my admin translated
urlpatterns = [
path('admin/', admin.site.urls),
]
urlpatterns += i18n_patterns (
path('i18n/', include('django.conf.urls.i18n')),
path('', include('pages.urls')),
path('cats', include('cats.urls')),
path('dogs', include('dogs.urls')),
prefix_default_language=False,
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The prefix_default_language=False,
this is optional and it removes the default language prefix from the url, which makes sense if you just got two or three languages. Although I did run into problems with this in the past, where the prefix_default_language=False,
did not work.
How to fix the problem with prefix_default_language=False,
NOT working, or not removing the default language prefix from urls
In my settings.py I changed:
LANGUAGE_CODE = 'en-us'
to LANGUAGE_CODE = 'en'
(seems to have solved it)
- Save image created via PIL to django model
- Does anyone know about workflow frameworks/libraries in Python?
- How to reload new update in Django project with Apache, mod_wsgi?
- What is Serializers to_internal_value method used for in Django
2👍
I know it’s not a solid solution but I needed a switch button (not a dropdown list since I want to toggle between two languages)
So I came up with this:
{% get_language_info_list for LANGUAGES as languages %}
{% if LANGUAGE_CODE == languages.0.code %}
<form action="{% url 'set_language' %}" method="post">
{% csrf_token %}
<div class="lang-btn">
<input name="next" type="hidden" value="{{ redirect_to }}" />
<input name="language" type="hidden" value="{{ languages.1.code }}" />
<button type="submit"><img width="30" src="{% static 'united-kingdom.png' %}" alt=""></button>
</div>
</form>
{% else %}
<form action="{% url 'set_language' %}" method="post">
{% csrf_token %}
<div class="lang-btn">
<input name="next" type="hidden" value="{{ redirect_to }}" />
<input name="language" type="hidden" value="{{ languages.0.code }}" />
<button type="submit"><img width="30" src="{% static 'turkey.png' %}" alt=""></button>
</div>
</form>
{% endif %}
- How should multiple Django apps communicate with each other?
- Django query with distinct and order_by
1👍
{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
<div class="btn-header">
<form action="{% url 'set_language' %}" method="post">
{% csrf_token %}
<input name="next" type="hidden" value="{{ redirect_to }}" />
{% for language in languages %}
{% if language.code != LANGUAGE_CODE %}
<button type="submit" name="language" value="{{ language.code }}">{{ language.name }}</button>
{% endif %}
{% endfor %}
</form>
</div>
if you have two languages. It will only show you the one that’s off.
- Django – Supervisor : exited too quickly
- Django admin: use checkboxes in list view in list_filter()
- How to override template in django-allauth?
0👍
Django 3.02
<div class="uk-flex">
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
<div class="languages">
<p>{% trans "Language" %}:</p>
<ul class="languages">
{% for language in languages %}
<li>
<a href="/{{ language.code }}/{{ request.get_full_path |slice:'4:'}}" {% if language.code == LANGUAGE_CODE %} class="selected"{% endif %}>
{{ language.name_local }}
</a>
</li>
{% endfor %}
</ul>
</div>
</div>
- Access Django devserver from another machine same network
- How to find out whether a model's column is a foreign key?
- Django Postgres ArrayField vs One-to-Many relationship
0👍
Seems lot of people have spend a lot of time (like myself) finding a proper solution that works for all cases. "Trick" is to set next = ''
if you want to reload existing page in different language. Citing from the django doc:
After setting the language choice, Django looks for a next parameter in the POST or GET data. If that is found and Django considers it to be a safe URL (i.e. it doesn’t point to a different host and uses a safe scheme), a redirect to that URL will be performed. Otherwise, Django may fall back to redirecting the user to the URL from the Referer header
Finally I wanted to have a function that I can call for any language changes triggered by links, buttons, dropdown menus or whatever. I ended up with this little js function:
django_language_set(language_code){
url = "{% url 'set_language' %}";
data = {
language: language_code,
next: '',
csrfmiddlewaretoken: '{{ csrf_token }}'
};
this.form_post(url, data)
}
form_post(path, params, method='post') {
/* simulates a post submit, call like:
form_post('/home', {language: 'de', next: ''})"
*/
const form = document.createElement('form');
form.method = method;
form.action = path;
for (const key in params) {
if (params.hasOwnProperty(key)) {
const hiddenField = document.createElement('input');
hiddenField.type = 'hidden';
hiddenField.name = key;
hiddenField.value = params[key];
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
Call the function, e.g.
<a @click="django_language_set('fr')">French</a>
0👍
I add a solution with buttons and the flags icon:
<form action="{% url 'set_language' %}" method="post">
{% csrf_token %}
{% get_current_language as LANGUAGE_CODE %}
<input name="next" type="hidden" value="{{ languageless_url }}" />
<a class="btn dropdown-sm-toggle" role="button" data-bs-toggle="dropdown" aria-expanded="false">
<img src="/static/img/flags/{{LANGUAGE_CODE}}.svg" width="20" height="30"></a>
</a>
<ul class="dropdown-menu dropdown-menu-end" id="language-list">
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<li>
<button class="dropdown-item" type="submit" name="language" value="{{ language.code }}"
class="{% if language.code == LANGUAGE_CODE %}selected{% endif %}">
<img src="/static/img/flags/{{ language.code }}.svg" width="20" height="30">
{#{{ language.code }}#}{{ language.name_local }}
</button>
</li>
{% endfor %}
</ul>
</form>
- Django: how to trigger creation of ContentTypes for new models?
- Django Form DateInput with widget in update: loosing the initial value
- Django – authentication, registration with email confirmation
- Django 'resolve' : get the url name instead of the view_function