Skip to content

Instantly share code, notes, and snippets.

@beaufour
Created November 30, 2012 16:00
Show Gist options
  • Save beaufour/4176623 to your computer and use it in GitHub Desktop.
Save beaufour/4176623 to your computer and use it in GitHub Desktop.
Django Middleware to choose language based on subdomain
import logging
from django.utils import translation
class SubdomainLanguageMiddleware(object):
"""
Set the language for the site based on the subdomain the request
is being served on. For example, serving on 'fr.domain.com' would
make the language French (fr).
"""
LANGUAGES = ['fr']
def process_request(self, request):
host = request.get_host().split('.')
if host and host[0] in self.LANGUAGES:
lang = host[0]
logging.debug("Choosing language: {0}".format(lang))
translation.activate(lang)
request.LANGUAGE_CODE = lang
@webjunkie
Copy link

You most likely need this as well to not run into really weird language issues:

def process_response(self, request, response):
    translation.deactivate()
    return response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment