I have already implemented a web page in English using Django. I now have a question when I'm trying to create a web page in Chinese. Pages in Chinese will be separated by prefix(/ch/).
I plan to implement a button to change the language, but the question is how Django remembers the changed page. Assuming my domain is 'domain.com', if the language is set to Chinese via the button I would like to have 'domain.com/ch' open when users access 'domain.com'. However, clicking on a button does not seem to be able to control the urlpatterns of Django(urls.py), and it seems necessary to store the variable corresponding to language in javascript.
I would appreciate your advice.
This is a fairly complex topic, but there's a lot of stuff to help in Django by default. Locale parts of django will look at cookies for language preferences & I believe there is also elements provided by the browser that it can pick up on for a default language to new visitors to a site.
In Django the thing to look out for is i18n and the docs on the topic are here; https://docs.djangoproject.com/en/1.11/topics/i18n/
You need to enable two settings for the best support of multiple languages; USE_I18N adds the language element, and USE_L10N allows for localised formatting of dates, numbers, currency etc.
On the topic of translations, give this a read as you need to make sure strings in your python code, javascript & templates that get shown to the user, are wrapped in the appropriate translation function.
In your root urls.py
file you'll also need to ensure you're using the i18n_patterns
which will prefix your URLs with the currently enabled language code. An example of it with the Javascript translation URL is;
from django.conf.urls.i18n import i18n_patterns
urlpatterns = i18n_patterns(
url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'),
)
Once you've got your settings sorted, URLs set to i18n_patterns
and some {% trans "" %}
tags in your templates you could test out the actual generation of the message catalogues.
You use two admin commands for this, the first is makemessages then you add the translations to the generated files, and run compilemessages
to finish the job.