Last active
March 25, 2025 14:26
-
-
Save vstoykov/1366794 to your computer and use it in GitHub Desktop.
Force Django to use settings.LANGUAGE_CODE for default language instead of request.META['HTTP_ACCEPT_LANGUAGE']
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try: | |
from django.utils.deprecation import MiddlewareMixin | |
except ImportError: | |
MiddlewareMixin = object | |
class ForceDefaultLanguageMiddleware(MiddlewareMixin): | |
""" | |
Ignore Accept-Language HTTP headers | |
This will force the I18N machinery to always choose settings.LANGUAGE_CODE | |
as the default initial language, unless another one is set via sessions or cookies | |
Should be installed *before* any middleware that checks request.META['HTTP_ACCEPT_LANGUAGE'], | |
namely django.middleware.locale.LocaleMiddleware | |
""" | |
def process_request(self, request): | |
if 'HTTP_ACCEPT_LANGUAGE' in request.META: | |
del request.META['HTTP_ACCEPT_LANGUAGE'] |
Yet another version:
from contextlib import suppress
from django.conf import settings
def inject_accept_language(get_response):
"""
Ignore Accept-Language HTTP headers.
This will force the I18N machinery to always choose
- Ukrainian for the main site
- ADMIN_LANGUAGE_CODE for the admin site
as the default initial language unless another one is set via
sessions or cookies.
Should be installed *before* any middleware that checks
request.META['HTTP_ACCEPT_LANGUAGE'], namely
`django.middleware.locale.LocaleMiddleware`.
"""
admin_lang = getattr(settings, 'ADMIN_LANGUAGE_CODE',
settings.LANGUAGE_CODE)
def middleware(request):
# Force Ukrainian locale for the main site
lang = admin_lang if request.path.startswith('/admin') else 'uk'
accept = request.META.get('HTTP_ACCEPT_LANGUAGE', []).split(',')
with suppress(ValueError):
# Remove `lang` from the HTTP_ACCEPT_LANGUAGE to avoid duplicates
accept.remove(lang)
accept = [lang] + accept
request.META['HTTP_ACCEPT_LANGUAGE'] = f"""{','.join(accept)}"""
return get_response(request)
return middleware
Yet another version:
from contextlib import suppress from django.conf import settings def inject_accept_language(get_response): """ Ignore Accept-Language HTTP headers. This will force the I18N machinery to always choose - Ukrainian for the main site - ADMIN_LANGUAGE_CODE for the admin site as the default initial language unless another one is set via sessions or cookies. Should be installed *before* any middleware that checks request.META['HTTP_ACCEPT_LANGUAGE'], namely `django.middleware.locale.LocaleMiddleware`. """ admin_lang = getattr(settings, 'ADMIN_LANGUAGE_CODE', settings.LANGUAGE_CODE) def middleware(request): # Force Ukrainian locale for the main site lang = admin_lang if request.path.startswith('/admin') else 'uk' accept = request.META.get('HTTP_ACCEPT_LANGUAGE', []).split(',') with suppress(ValueError): # Remove `lang` from the HTTP_ACCEPT_LANGUAGE to avoid duplicates accept.remove(lang) accept = [lang] + accept request.META['HTTP_ACCEPT_LANGUAGE'] = f"""{','.join(accept)}""" return get_response(request) return middleware
Thank you for this version. But it has issue
accept = request.META.get('HTTP_ACCEPT_LANGUAGE', []).split(',')
It will crash with error 'list' object has no attribute 'split'. I think it should be instead
accept = request.META.get('HTTP_ACCEPT_LANGUAGE', "").split(',')
@dismine Yes, you're right! 👍
Thank You so much @vstoykov!
thanks, saved my day
Thanks everybody involved!
With the new middleware format:
class ForceDefaultLanguageMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if 'HTTP_ACCEPT_LANGUAGE' in request.META:
del request.META['HTTP_ACCEPT_LANGUAGE']
return self.get_response(request)
With the new middleware format:
class ForceDefaultLanguageMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if 'HTTP_ACCEPT_LANGUAGE' in request.META: del request.META['HTTP_ACCEPT_LANGUAGE'] return self.get_response(request)
Thanks, u save my day
14 years later, and people are still using this. Perhaps I should pack it into a real repo with a bunch of other Django recipes )
Because the sad reality is that nobody is configuring their browser properly to ask websites for content on their preffered language. The easy fix is every site owner to force users to use some specific language.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. I added this middleware before any other middleware that is using language code and it works now.