'URL and page refresh issue for Multilingual site on Django
plz help me to solve one issue. I have a Multilingual site on Django with standart internationalization framework.
Settings.py
MIDDLEWARE = [
...
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware'
...]
LANGUAGES = (
('en', _('English')),
('ja', _('Japanese')),
)
LANGUAGE_CODE = 'en'
USE_I18N = True
USE_L10N = True
LOCALE_PATHS = ['../locale/']
All *.mo and *.po files for both languages are successfully created.
main.html has a code snippet for language switching:
{% get_current_language as CURRENT_LANGUAGE %}
{% get_available_languages as AVAILABLE_LANGUAGES %}
{% get_language_info_list for AVAILABLE_LANGUAGES as languages %}
<div class="languages">
<p>{% trans "Language" %}:</p>
<ul class="languages">
{% for language in languages %}
<li>
<a href="/{{ language.code }}/"
{% if language.code == CURRENT_LANGUAGE %} class="active"{% endif %}>
{{ language.name_local }}
</a>
</li>
{% endfor %}
</ul>
</div>
url.py
urlpatterns = i18n_patterns(
path('', include('mysite.urls'))
)
simplified website structure
main.html
--page1.html
--page2.html
Now I can click and change the page translation, but I've faced with next issue. When I switch the language, e.g. from main/en/page1 I redirected back to the main/ja page, regardless my current location on a website structure. In other words, I'd like to stay at the same page1 when I switch the language and change only the language prefix main/en/page1 -> main/ja/page1. The best working example is DjangoDocs witch has the language switcher on the bottom-right position and works perfect.
Solution 1:[1]
Resolved the issue. Just add line {{ request.get_full_path |slice:'4:'}} to the <a href=> part.
{% get_available_languages as AVAILABLE_LANGUAGES %}
{% get_language_info_list for AVAILABLE_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 == CURRENT_LANGUAGE %} class="active"{% endif %}>
{{ language.name_local }}
</a>
</li>
{% endfor %}
</ul>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vlad Stenkin |
