99
To quote parts from Djangoβs Locale Middleware (django.middleware.locale.LocaleMiddleware
):
from django.utils import translation
class LocaleMiddleware(object):
"""
This is a very simple middleware that parses a request
and decides what translation object to install in the current
thread context. This allows pages to be dynamically
translated to the language the user desires (if the language
is available, of course).
"""
def process_request(self, request):
language = translation.get_language_from_request(request)
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
The translation.activate(language)
is the important bit.
15
Be sure to also add deactivate in process_response, otherwise you will have problems with different threads.
from django.utils import translation
class LocaleMiddleware(object):
"""
This is a very simple middleware that parses a request
and decides what translation object to install in the current
thread context. This allows pages to be dynamically
translated to the language the user desires (if the language
is available, of course).
"""
def process_request(self, request):
language = translation.get_language_from_request(request)
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
def process_response(self, request, response):
translation.deactivate()
return response
- [Django]-Can django's auth_user.username be varchar(75)? How could that be done?
- [Django]-Automated django receive hook on server: respond to collectstatic with "yes"
- [Django]-Django urls without a trailing slash do not redirect
7
If just want to get the translated strings for a language for whatever reason, you can use override
as a decorator like this:
from django.utils import translation
from django.utils.translation import ugettext as _
with translation.override(language):
welcome = _('welcome')
- [Django]-Making a Django form class with a dynamic number of fields
- [Django]-Add Indexes (db_index=True)
- [Django]-Django MEDIA_URL and MEDIA_ROOT
5
You can consider storing the language in the user model and use this custom middleware django-user-language-middleware.
This allows easy translation of your Django app by looking at the selected language in the user.language
field and you can always know the language preference of any user.
Usage:
-
Add a language field to your user model:
class User(auth_base.AbstractBaseUser, auth.PermissionsMixin): # ... language = models.CharField(max_length=10, choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE)
-
Install the middleware from pip:
pip install django-user-language-middleware
-
Add it to your middleware class list in settings to listen to requests:
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10 ... 'user_language_middleware.UserLanguageMiddleware', ... ]
I hope this may help people landing on this question in the future.
- [Django]-ImportError: No module named 'django.core.urlresolvers'
- [Django]-How to filter empty or NULL names in a QuerySet?
- [Django]-The right place to keep my signals.py file in a Django project
3
Sometimes you want to enforce a certain language for a given view but let the browser language settings choice the language for the rest of the views. I havenβt figured out how to change the language in the view code but you can do this by implementing a simple Middleware
lang_based_on_url_middleware.py:
from django.utils import translation
# Dictionary of urls that should use special language regardless of language set in browser
# key = url
# val = language code
special_cases = {
'/this/is/some/url/' : 'dk',
'/his/is/another/special/case' : 'de',
}
class LangBasedOnUrlMiddleware(object):
def process_request(self, request):
if request.path_info in special_cases:
lang = special_cases[request.path_info]
translation.activate(lang)
request.LANGUAGE_CODE = lang
In settings.py:
MIDDLEWARE_CLASSES = (
...
'django.middleware.locale.LocaleMiddleware',
'inner.lang_based_on_url_middleware.LangBasedOnUrlMiddleware', # remember that the order of LocaleMiddleware and LangBasedOnUrlMiddleware matters
...
)
Not an elegant solution but it works.
- [Django]-What is the clean way to unittest FileField in django?
- [Django]-Do django db_index migrations run concurrently?
- [Django]-Django models: mutual references between two classes and impossibility to use forward declaration in python
3
If you are using django 1.10 or higher, thereβs a new syntax for custom middleware:
from django.utils import translation
class LocaleMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
language_code = 'en' #TODO, your logic
translation.activate(language_code)
response = self.get_response(request)
translation.deactivate()
return response
- [Django]-Difference between User.objects.create_user() vs User.objects.create() vs User().save() in django
- [Django]-Reducing Django Memory Usage. Low hanging fruit?
- [Django]-Django Model Fields Indexing
- [Django]-Django models avoid duplicates
- [Django]-"No module named simple" error in Django
- [Django]-Django test app error β Got an error creating the test database: permission denied to create database
0
With class based views, this should work:
class YourView(SomeBuiltInView):
def get(self, request, *args, **kwargs):
setattr(request, 'LANGUAGE_CODE', 'YOUR_LANGUAGE_CODE')
return super().get(self, request, *args, **kwargs)
Basically all you do is make the view renderer think that the request came from YOUR_LANGUAGE_CODE
rather than what was originally true.
- [Django]-What is a NoReverseMatch error, and how do I fix it?
- [Django]-Creating Custom Filters for list_filter in Django Admin
- [Django]-Sending an SMS to a Cellphone using Django