简体   繁体   中英

how to use multiple domains and mask a django project

I have a Django website that's configured on a particular domain example.com . Now I'm planning to use the same website for different countries where I have to use their language. For example China, I'm planning to create a sub domain chinese.example.com which will point to exactly the same example.com project but the language will be switched to chinese. Also I would like to mask this chinese.example.com sub domain with another domain chinaexample.com . Please advise how to accomplish this using Apache & Django.

First step - make sure that all of your domains are added into 'ALLOWED_HOSTS' in django config.

Next - if you will have some content that will be available only for particular domain, it will be handy to use sites framework built into django. But if you want to have one language on multiple domains and want some content to be available for language, not for domain, better solution might be to create own method for assigning content to domain (or language).

Third step - write middleware that will check your domain and activate language assigned to it. Example middleware can look like this:

class DomainLanguageMiddleware:

    def process_request(self, request):

        try:
            host = request.META['HTTP_HOST']
            host_port = host.split(':')
            if len(host_port) == 2:
                host = host_port[0]

            if host in settings.LANG_MAP:
                request.LANG = settings.LANG_MAP[host]
                translation.activate(request.LANG)
                request.LANGUAGE_CODE = request.LANG
        except KeyError:
            pass

This code is using LANG_MAP setting, that should be an dictionary containing domain as key and language assigned to that domain as value.

Using that solution, all domains or subdomains can point to one django instance, with one settings.py file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM