mariepiercm
mariepiercm

Reputation: 119

How to localize a multi site django app based on the domain?

I have one Django project, one website, but each translation is represented by a domains, drenglish.com for english, drspanish.com for spanish and drportuguese.com for portuguese.

There is only one admin, one database

i see with most host for django (2.0 and python 3.7) y your need to host throught ssh linux(putty).

but how can i make the 3 domains work at the same time ?

sorry for the noob question its my first time putting a website up

if any help that is the middleware i use to detect the domain and offer the right language

class SetLanguageToDomain:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        current_site = get_current_site(request).domain
        if current_site == 'www.drportuguese.com':
            user_language = 'pt_BR'
        elif current_site == 'www.drspanish.com':
            user_language = 'es_ES'
        else:
            user_language = 'en'
        translation.activate(user_language)
        request.session[translation.LANGUAGE_SESSION_KEY] = user_language

        response = self.get_response(request)

        return response

Upvotes: 1

Views: 208

Answers (2)

Karim N Gorjux
Karim N Gorjux

Reputation: 3033

Django uses this middleware django.middleware.locale.LocaleMiddleware to understand which language use to render your response. If you check the code, there is a call to a function in the module translation: get_language_from_path.

This is the source code of the function

language_code_prefix_re = re.compile(r'^/(\w+([@-]\w+)?)(/|$)')

def get_language_from_path(path, strict=False):
    """
    Return the language code if there's a valid language code found in `path`.
    If `strict` is False (the default), look for a country-specific variant
    when neither the language code nor its generic variant is found.
    """
    regex_match = language_code_prefix_re.match(path)
    if not regex_match:
        return None
    lang_code = regex_match.group(1)
    try:
        return get_supported_language_variant(lang_code, strict=strict)
    except LookupError:
        return None

To find the match, django uses the LANGUAGES setting of your project to find something like it-IT, you can check the code of the LocalMiddleWare and the get_language_from_path to change the middleware to your needs.

Upvotes: 2

grrrrrr
grrrrrr

Reputation: 1425

You would need to have the three different domains point to the same server in your DNS (docs for AWS and Heroku). Make sure all 3 are in your ALLOWED_HOSTS in your settings and then in your views you can access the host through the meta on the request:

request.META['HTTP_HOST']

Also possibly relevant for your project is request.META['HTTP_ACCEPT_LANGUAGE']

Upvotes: 1

Related Questions