Detect the language & django locale-url

前端 未结 3 1686
北海茫月
北海茫月 2021-02-01 11:31

I want to deploy a website in english & spanish and detect the user browser language & redirect to the correct locale site.

My site is www.elmalabarista.com

3条回答
  •  旧时难觅i
    2021-02-01 11:56

    really it should be like this:

    There can be multiple languages accepted by order of preference

    def process_request(self, request):
        locale, path = utils.strip_path(request.path_info)
        if (not locale) or (locale==''):
            if request.META.has_key('HTTP_ACCEPT_LANGUAGE'):
            l = [x.strip()[:2] for x in request.META['HTTP_ACCEPT_LANGUAGE'].split(',')]
            for lang_code in l:
                    locale = utils.supported_language(lang_code)
                    if locale:
              break
            else:
                locale = settings.LANGUAGE_CODE
        locale_path = utils.locale_path(path, locale)
        if locale_path != request.path_info:
            if request.META.get("QUERY_STRING", ""):
                locale_path = "%s?%s" % (locale_path,
                        request.META['QUERY_STRING'])
            return HttpResponseRedirect(locale_path)
        request.path_info = path
        if not locale:
            try:
                locale = request.LANGUAGE_CODE
            except AttributeError:
                locale = settings.LANGUAGE_CODE
        translation.activate(locale)
        request.LANGUAGE_CODE = translation.get_language()
    

提交回复
热议问题