I am trying to change the language of the website when users click a button in Django.
I have a base project and the urls are:
urlpatterns += i18n_patterns(
# Ecommerce is the app where I want to change the language
url(r'^', include("ecommerce.urls")),
)
The url inside Ecommerce.urls is:
urlpatterns = [
url(r'^testing/$', views.test, name='url_testing'),
... other urls
]
When I visit the url above, I first go to: http://localhost/en/testing/
.
I want to set a link <a href="{% url 'url_testing' %}">Change Language</a>
so that when users click it, it will change language to http://localhost/zh-hans/testing/
. How do I do this in my template?
EDIT
I can now change the language using the following code but the problem is that it only works once:
<form id="languageForm" action="/i18n/setlang/" method="post">
{% csrf_token %}
<input name="next" type="hidden" value="{% url 'url_testing' %}" />
<input id="newLanguageInput" type="hidden" name="language"/>
</form>
And my links are:
<li><a onclick="changeLanguage('zh-hans')">简体</a></li>
<li><a onclick="changeLanguage('zh-hant')">繁體</a></li>
The function changeLanguage is defined like:
function changeLanguage(newLanguage) {
$('input[name="newLanguageInput"]').val(newLanguage);
$('#languageForm').submit();
}
The code works when I first click any of the 2 links, and I will be redirected to the url http://localhost/zh-hans/testing/
or http://localhost/zh-hant/testing/
. The problem is after I change the language once, it no longer changes. Is there something wrong with my submit?
Actually it's not going to be a simple <a>
link but a <form>
.
Have a read on how to set_language
redirect view. This form will be responsible for changing languages. It's easy as a pie.
Make sure you have set some LANGUAGES
first.