Django has great support for localization and internationalization
(check django docs for more info) and django provides a usefull middleware
named LocaleMiddleware
which automatically sets response language based on
current request.
(based on requested url, session, cookies and request headers in respected order.
look at this page to understand how LocaleMiddleware
works).
The issue is, I want to get user language prefrences from their profile instead of using cookies or session, assume your profile model is something like this:
class Profile(models.Model)
LANGUAGE_FA = "fa"
LANGUAGE_EN = "en"
LANGUAGE_CHOICES = [
(LANGUAGE_FA, _("Persian")),
(LANGUAGE_EN, _("English")),
]
user = models.OneToOneField(
User,
on_delete=models.CASCADE,
)
language = models.CharField(
choices=LANGUAGE_CHOICES,
max_length=2,
blank=True,
)
# other stuff
How should I set langague for each user based on this model, the simple and bad
solution is to set_lanauage
for each view. your code will be something like this:
def my_view(*args, **kwargs):
translation.activate(
request.user.profile.language
)
# rest of the view here
but issue with solution above is you should manually set language code for every view. simpler solution is to manually write your own middle ware, your middleware is very simple:
from django.utils import translation
from django.utils.deprecation import MiddlewareMixin
class MyLocaleMiddleware(MiddlewareMixin):
def process_request(self, request):
if request.user.is_authenticated and request.user.profile.language:
translation.activate(request.user.profile.language)
request.LANGUAGE_CODE = translation.get_language()
and then add your middleware to MIDDLEWARE
settings, note that it should be
somewhere below AuthenticationMiddleware
:
MIDDLEWARE = [
# other middlewares
'django.contrib.auth.middleware.AuthenticationMiddleware',
'path.to.MyLocaleMiddleware',
# other middlewares
]
after that every time a user tries to view a page it will be localized based on their profile settings.