Reputation: 2131
I'm trying to use django-multilingual and setup it properly. But what I found is that everything is clear for django-multilingual except a template usage example.
I just started to use django and I don't know, maybe because of this reason, I cannot figure out how to switch between languages on template side.
Is there any example that you can give or any 'more' clear source/documentation about this?
Upvotes: 8
Views: 16797
Reputation: 1
You can create i18n switcher following The set_language redirect view but first, you better set up translation(English and French) following my answer and you can see my question and my answer explaining how to create i18n switcher for Django Admin. *I use Django 4.2.1.
Then, add path("i18n/", include("django.conf.urls.i18n"))
to urlpatterns
in core/settings.py
as shown below. *You should not include path("i18n/", include("django.conf.urls.i18n"))
in i18n_patterns()
to work correctly according to the doc:
# "core/settings.py"
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.i18n import i18n_patterns
urlpatterns = i18n_patterns(
path('admin/', admin.site.urls),
path("my_app1/", include('my_app1.urls')),
)
# ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ Here ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
urlpatterns += [
path("i18n/", include("django.conf.urls.i18n"))
]
Then, add <form action="{% url 'set_language' %}" ...>...</form>
to templates/index.html
as shown below:
{% "templates/index.html" %}
{% load i18n %}
{% ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ Here ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ %}
<form action="{% url 'set_language' %}" method="post">{% csrf_token %}
<input name="next" type="hidden" value="{{ redirect_to }}">
<select name="language">
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}>
{{ language.name_local }} ({{ language.code }})
</option>
{% endfor %}
</select>
<input type="submit" value="Go">
</form>
{% ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ Here ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ %}
{% translate "Hello" %} {% trans "World" %}
Now, you can switch English to French as shown below:
And, you can switch French to English as shown below:
Upvotes: 0
Reputation: 10311
switching locale in django is a simple post do this view
https://docs.djangoproject.com/en/dev/topics/i18n/translation/#the-set-language-redirect-view
in templates you can access the language value with request.LANGUAGE_CODE
Upvotes: 6
Reputation: 594
You might also want to try django-localeurl app. It enables users to switch locales storing current locale in the URL. It also provides several useful template tags for switching and displaying available locales.
Upvotes: 4