Skip to content

Instantly share code, notes, and snippets.

@vstoykov
Last active March 25, 2025 14:26
Show Gist options
  • Save vstoykov/1366794 to your computer and use it in GitHub Desktop.
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']
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']
@ionsurdu
Copy link

thanks, saved my day

@andre-fuchs
Copy link

Thanks everybody involved!

@ismoz
Copy link

ismoz commented Mar 19, 2025

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) 

@nigrumdiaster
Copy link

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

@IlianIliev
Copy link

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 )

@vstoykov
Copy link
Author

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