Skip to content

Instantly share code, notes, and snippets.

@bjinwright
Forked from beaufour/language.py
Last active May 17, 2017 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjinwright/8499a8266ab36e912126270779ed650a to your computer and use it in GitHub Desktop.
Save bjinwright/8499a8266ab36e912126270779ed650a to your computer and use it in GitHub Desktop.
Django Middleware to choose language based on subdomain
import logging
from django.utils import translation
from django.conf import settings
class DomainBasedLanguageMiddleware(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).
"""
def process_request(self, request):
host = request.get_host()
if host in settings.LANGUAGE_DOMAINS:
lang = settings.LANGUAGE_DOMAINS.get(host)
logging.debug("Choosing language: {0}".format(lang))
translation.deactivate()
translation.activate(lang)
request.LANGUAGE_CODE = lang
# Add this setting with real hostnames.
LANGUAGE_DOMAINS.update({'127.0.0.1:8000':'en','127.0.0.1:8001':'en_GB'})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment