Пример #1
0
def change_locale(request):
    """
    Redirect to a given url while changing the locale in the path
    The url and the locale code need to be specified in the
    request parameters.
    """
    
    # we assume the target url shares the same script name !
    script_name = request.META["SCRIPT_NAME"] 
    
    next = request.REQUEST.get('next', None)
    if not next:
        next = urlsplit(request.META.get('HTTP_REFERER', None))[2]
    if not next:
        next = request.META["SCRIPT_NAME"]+"/" # root of the django project
    
    if not next.startswith(script_name):
        script_name = ""
        locale, path_info = utils.strip_path(next)
    else:
        locale, path_info = utils.strip_path(next[len(script_name):])
     
     
    if request.method == 'POST':
        locale = request.POST.get('locale', None)   
        if locale and check_for_language(locale):
            path = utils.locale_path(path, locale, script_name)
            response = http.HttpResponseRedirect(path)
            return response
    
    return http.HttpResponseRedirect(next) # we failed language change    
Пример #2
0
    def process_request(self, request):
        locale, path = utils.strip_path(request.path_info)
        if localeurl_settings.USE_ACCEPT_LANGUAGE and not locale:
            accept_langs = filter(lambda x: x, [
                utils.supported_language(lang[0])
                for lang in parse_accept_lang_header(
                    request.META.get('HTTP_ACCEPT_LANGUAGE', ''))
            ])
            if accept_langs:
                locale = accept_langs[0]
        locale_path = utils.locale_path(path, locale)
        if locale_path != request.path_info:
            locale_url = utils.add_script_prefix(locale_path)

            qs = request.META.get("QUERY_STRING", "")
            if qs:
                # Force this to remain a byte-string by encoding locale_path
                # first to avoid Unicode tainting - downstream will need to
                # handle the job of handling in-the-wild character encodings:
                locale_url = "%s?%s" % (locale_path.encode("utf-8"), qs)

            redirect_class = HttpResponsePermanentRedirect
            if not localeurl_settings.LOCALE_REDIRECT_PERMANENT:
                redirect_class = HttpResponseRedirect
            # @@@ iri_to_uri for Django 1.0; 1.1+ do it in HttpResp...Redirect
            return redirect_class(iri_to_uri(locale_url))
        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()
Пример #3
0
 def process_request(self, request):
     locale, path = utils.strip_path(request.path_info)
     if localeurl_settings.USE_ACCEPT_LANGUAGE and not locale:
         accept_langs = filter(lambda x: x, [
             utils.supported_language(lang[0])
             for lang in parse_accept_lang_header(
                 request.META.get('HTTP_ACCEPT_LANGUAGE', ''))
         ])
         if accept_langs:
             locale = accept_langs[0]
     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'])
         locale_url = utils.add_script_prefix(locale_path)
         redirect_class = HttpResponsePermanentRedirect
         if not localeurl_settings.LOCALE_REDIRECT_PERMANENT:
             redirect_class = HttpResponseRedirect
         # @@@ iri_to_uri for Django 1.0; 1.1+ do it in HttpResp...Redirect
         return redirect_class(iri_to_uri(locale_url))
     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()
Пример #4
0
def change_locale(request):
    """
    Redirect to a given url while changing the locale in the path
    The url and the locale code need to be specified in the
    request parameters.
    """
    next = request.REQUEST.get('next', None)
    if not next:
        referrer = request.META.get('HTTP_REFERER', None)
        if referrer:
            next = urlsplit(referrer)[2]
    if not next:
        next = '/'
    _, path = utils.strip_path(next)
    if request.method == 'POST':
        locale = request.POST.get('locale', None)
        if locale and check_for_language(locale):
            if localeurl_settings.USE_SESSION:
                request.session['django_language'] = locale
            path = utils.locale_path(path, locale)
            signals.locale_change.send(sender=change_locale,
                                       locale=locale,
                                       user=request.user)

    response = http.HttpResponseRedirect(path)
    return response
Пример #5
0
def alternate_languages(context):
    request = context['request']

    is_lang = False
    lang_list = []
    alternate = ""
    for lang in settings.LANGUAGES:
        lang_regex = ("/%s/") % lang[0]
        if lang_regex in request.path:
            is_lang = True
        else:
            lang_list.append(lang[0])

    if hasattr(request, 'urlconf') and request.urlconf is not None:
        urlconf = request.urlconf
    else:
        urlconf = get_urlconf()
    locale, path = utils.strip_path(request.path_info)
    hostname = request.get_host().split(":")[0]

    if is_lang:
        for lang in lang_list:
            locale_path = utils.locale_path(path,
                                            lang,
                                            host=hostname,
                                            urlconf=urlconf)
            alternate += (
                '<link rel="alternate" hreflang="%s" href="http://%s%s" />\n'
            ) % (lang, hostname, locale_path)
    return alternate
Пример #6
0
 def process_request(self, request):
     locale, path = utils.strip_path(request.path_info)
     if localeurl_settings.USE_ACCEPT_LANGUAGE and not locale:
         accept_langs = filter(lambda x: x, [utils.supported_language(lang[0])
                                             for lang in
                                             parse_accept_lang_header(
                     request.META.get('HTTP_ACCEPT_LANGUAGE', ''))])
         if accept_langs:
             locale = accept_langs[0]
     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'])
         locale_url = utils.add_script_prefix(locale_path)
         # @@@ iri_to_uri for Django 1.0; 1.1+ do it in HttpResp...Redirect
         return HttpResponsePermanentRedirect(iri_to_uri(locale_url))
     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()
Пример #7
0
def alternate_languages(context):
    request = context['request']

    is_lang = False
    lang_list = []
    alternate = ""
    for lang in settings.LANGUAGES:
        lang_regex = ("/%s/") % lang[0]
        if lang_regex in request.path:
            is_lang = True
        else:
            lang_list.append(lang[0])

    if hasattr(request, 'urlconf') and request.urlconf is not None:
            urlconf = request.urlconf
    else:
        urlconf = get_urlconf()
    locale, path = utils.strip_path(request.path_info)
    hostname = request.get_host().split(":")[0]

    if is_lang:
        for lang in lang_list:
            locale_path = utils.locale_path(path, lang, host=hostname, urlconf=urlconf)
            alternate += ('<link rel="alternate" hreflang="%s" href="http://%s%s" />\n') % (lang, hostname ,locale_path)
    return alternate
Пример #8
0
    def process_request(self, request):
        locale, path = utils.strip_path(request.path_info)
        if localeurl_settings.USE_ACCEPT_LANGUAGE and not locale:
            accept_langs = filter(lambda x: x, [utils.supported_language(lang[0])
                                                for lang in
                                                parse_accept_lang_header(
                        request.META.get('HTTP_ACCEPT_LANGUAGE', ''))])
            if accept_langs:
                locale = accept_langs[0]
        locale_path = utils.locale_path(path, locale)
        if locale_path != request.path_info:
            locale_url = utils.add_script_prefix(locale_path)

            qs = request.META.get("QUERY_STRING", "")
            if qs:
                # Force this to remain a byte-string by encoding locale_path
                # first to avoid Unicode tainting - downstream will need to
                # handle the job of handling in-the-wild character encodings:
                locale_url = "%s?%s" % (locale_path.encode("utf-8"), qs)

            redirect_class = HttpResponsePermanentRedirect
            if not localeurl_settings.LOCALE_REDIRECT_PERMANENT:
                redirect_class = HttpResponseRedirect
            # @@@ iri_to_uri for Django 1.0; 1.1+ do it in HttpResp...Redirect
            return redirect_class(iri_to_uri(locale_url))
        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()
Пример #9
0
 def process_request(self, request):
     locale, path = self.split_locale_from_request(request)
     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:
         locale = settings.LANGUAGE_CODE
     translation.activate(locale)
     request.LANGUAGE_CODE = translation.get_language()
Пример #10
0
    def process_request(self, request):
        hostname = request.get_host().split(":")[0]

        locale, path = utils.strip_path(request.path_info)
        if localeurl_settings.USE_SESSION and not locale:
            slocale = request.session.get('django_language')
            if slocale and utils.supported_language(slocale):
                locale = slocale
        if localeurl_settings.USE_ACCEPT_LANGUAGE and not locale:
            accept_lang_header = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
            header_langs = parse_accept_lang_header(accept_lang_header)
            accept_langs = filter(
                None,
                [utils.supported_language(lang[0]) for lang in header_langs])
            if accept_langs:
                locale = accept_langs[0]

        if hasattr(request, 'urlconf') and request.urlconf is not None:
            urlconf = request.urlconf
        else:
            urlconf = get_urlconf()

        locale_path = utils.locale_path(path,
                                        locale,
                                        host=hostname,
                                        urlconf=urlconf)
        # locale case might be different in the two paths, that doesn't require
        # a redirect (besides locale they'll be identical anyway)
        if locale_path.lower() != request.path_info.lower():
            locale_url = utils.add_script_prefix(locale_path)

            qs = request.META.get("QUERY_STRING", "")
            if qs:
                # Force this to remain a byte-string by encoding locale_path
                # first to avoid Unicode tainting - downstream will need to
                # handle the job of handling in-the-wild character encodings:
                locale_url = "%s?%s" % (locale_path.encode("utf-8"), qs)

            redirect_class = HttpResponsePermanentRedirect
            if not localeurl_settings.LOCALE_REDIRECT_PERMANENT:
                redirect_class = HttpResponseRedirect
            # @@@ iri_to_uri for Django 1.0; 1.1+ do it in HttpResp...Redirect
            return redirect_class(iri_to_uri(locale_url))
        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()
Пример #11
0
    def process_request(self, request):                        
        locale, path = self.split_locale_from_request(request)
        locale_path = utils.locale_path(path, locale or translation.get_language_from_request(request) \
                                        or translation.get_language())

        if locale_path != request.path_info:
            if request.META.get("QUERY_STRING", ""):
                locale_path = u"%s?%s" % (locale_path, request.META['QUERY_STRING'])
            return HttpResponseRedirect(locale_path)
        request.path_info = path
        if not locale:
            locale = translation.get_language() or settings.LANGUAGE_CODE
        translation.activate(locale)
        request.LANGUAGE_CODE = translation.get_language()
Пример #12
0
    def process_request(self, request):
        hostname = request.get_host().split(":")[0]

        locale, path = utils.strip_path(request.path_info)
        if localeurl_settings.USE_SESSION and not locale:
            slocale = request.session.get('django_language')
            if slocale and utils.supported_language(slocale):
                locale = slocale
        if localeurl_settings.USE_ACCEPT_LANGUAGE and not locale:
            accept_lang_header = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
            header_langs = parse_accept_lang_header(accept_lang_header)
            accept_langs = filter(
                None,
                [utils.supported_language(lang[0]) for lang in header_langs]
                )
            if accept_langs:
                locale = accept_langs[0]

        if hasattr(request, 'urlconf') and request.urlconf is not None:
            urlconf = request.urlconf
        else:
            urlconf = get_urlconf()

        locale_path = utils.locale_path(path, locale, host=hostname, urlconf=urlconf)
        # locale case might be different in the two paths, that doesn't require
        # a redirect (besides locale they'll be identical anyway)
        if locale_path.lower() != request.path_info.lower():
            locale_url = utils.add_script_prefix(locale_path)

            qs = request.META.get("QUERY_STRING", "")
            if qs:
                # Force this to remain a byte-string by encoding locale_path
                # first to avoid Unicode tainting - downstream will need to
                # handle the job of handling in-the-wild character encodings:
                locale_url = "%s?%s" % (locale_path.encode("utf-8"), qs)

            redirect_class = HttpResponsePermanentRedirect
            if not localeurl_settings.LOCALE_REDIRECT_PERMANENT:
                redirect_class = HttpResponseRedirect
            # @@@ iri_to_uri for Django 1.0; 1.1+ do it in HttpResp...Redirect
            return redirect_class(iri_to_uri(locale_url))
        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()
Пример #13
0
 def test_locale_url(self):
     # We'd like to be able to test using settings.FORCE_SCRIPT_NAME, but
     # the urlresolvers module caches the prefix.
     script_name = urlresolvers.get_script_prefix()
     self.assertEqual(script_name + 'en/about/localeurl/',
             utils.locale_url('/about/localeurl/'))
     self.assertEqual(script_name + 'en/about/localeurl/',
             utils.locale_url('/about/localeurl/', 'de'))
     self.assertEqual(script_name + 'en/about/localeurl/',
             utils.locale_url('/about/localeurl/', 'en'))
     self.assertEqual(script_name + 'en/about/localeurl/',
             utils.locale_url('/about/localeurl/', 'en-us'))
     self.assertEqual(script_name + 'nl-nl/about/localeurl/',
             utils.locale_url('/about/localeurl/', 'nl-nl'))
     self.assertEqual(script_name + 'test/independent/bla/bla',
             utils.locale_path('/test/independent/bla/bla', 'en'))
Пример #14
0
 def process_request(self, request):
     locale, path = utils.strip_path(request.path_info)
     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()
Пример #15
0
 def test_locale_url(self):
     # We'd like to be able to test using settings.FORCE_SCRIPT_NAME, but
     # the urlresolvers module caches the prefix.
     script_name = urlresolvers.get_script_prefix()
     self.assertEqual(script_name + 'en/about/localeurl/',
                      utils.locale_url('/about/localeurl/'))
     self.assertEqual(script_name + 'en/about/localeurl/',
                      utils.locale_url('/about/localeurl/', 'de'))
     self.assertEqual(script_name + 'en/about/localeurl/',
                      utils.locale_url('/about/localeurl/', 'en'))
     self.assertEqual(script_name + 'en/about/localeurl/',
                      utils.locale_url('/about/localeurl/', 'en-us'))
     self.assertEqual(script_name + 'nl-nl/about/localeurl/',
                      utils.locale_url('/about/localeurl/', 'nl-nl'))
     self.assertEqual(script_name + 'test/independent/bla/bla',
                      utils.locale_path('/test/independent/bla/bla', 'en'))
Пример #16
0
 def test_locale_path(self):
     self.assertEqual('/en/about/localeurl/',
                      utils.locale_path('/about/localeurl/'))
     self.assertEqual('/en/about/localeurl/',
                      utils.locale_path('/about/localeurl/', 'de'))
     self.assertEqual('/en/about/localeurl/',
                      utils.locale_path('/about/localeurl/', 'en'))
     self.assertEqual('/en/about/localeurl/',
                      utils.locale_path('/about/localeurl/', 'en-us'))
     self.assertEqual('/nl-nl/about/localeurl/',
                      utils.locale_path('/about/localeurl/', 'nl-nl'))
     self.assertEqual('/test/independent/bla/bla',
                      utils.locale_path('/test/independent/bla/bla', 'en'))
Пример #17
0
 def test_locale_path(self):
     self.assertEqual('/en/about/localeurl/',
             utils.locale_path('/about/localeurl/'))
     self.assertEqual('/en/about/localeurl/',
             utils.locale_path('/about/localeurl/', 'de'))
     self.assertEqual('/en/about/localeurl/',
             utils.locale_path('/about/localeurl/', 'en'))
     self.assertEqual('/en/about/localeurl/',
             utils.locale_path('/about/localeurl/', 'en-us'))
     self.assertEqual('/nl-nl/about/localeurl/',
             utils.locale_path('/about/localeurl/', 'nl-nl'))
     self.assertEqual('/test/independent/bla/bla',
             utils.locale_path('/test/independent/bla/bla', 'en'))
Пример #18
0
def change_locale(request):
    """
    Redirect to a given url while changing the locale in the path
    The url and the locale code need to be specified in the
    request parameters.
    """
    next = request.REQUEST.get("next", None)
    if not next:
        next = urlsplit(request.META.get("HTTP_REFERER", None))[2]
    if not next:
        next = "/"
    _, path = utils.strip_path(next)
    if request.method == "POST":
        locale = request.POST.get("locale", None)
        if locale and check_for_language(locale):
            path = utils.locale_path(path, locale)

    response = http.HttpResponseRedirect(path)
    return response
Пример #19
0
def change_locale(request):
    """
    Redirect to a given url while changing the locale in the path
    The url and the locale code need to be specified in the
    request parameters.
    """
    next = request.REQUEST.get('next', None)
    if not next:
        next = urlsplit(request.META.get('HTTP_REFERER', None))[2]
    if not next:
        next = '/'
    _, path = utils.strip_path(next)
    if request.method == 'POST':
        locale = request.POST.get('locale', None)
        if locale and check_for_language(locale):
            path = utils.locale_path(path, locale)

    response = http.HttpResponseRedirect(path)
    return response
Пример #20
0
def direct_to_template(request, template, extra_context=None, mimetype=None, **kwargs):
  """
    Render a given template with any extra URL parameters in the context as
    ``{{ params }}``.
  """
  if extra_context is None: extra_context = {}
  dictionary = {'params': kwargs}
  for key, value in extra_context.items():
    if callable(value):
      dictionary[key] = value()
    else:
      dictionary[key] = value
  if locale_path:
    for url_name in ('LOGIN_REDIRECT_URL', 'LOGOUT_REDIRECT_URL'):
      url = locale_path(settings.__dict__.get(url_name), request.LANGUAGE_CODE)
      dictionary[url_name] = url
  c = RequestContext(request, dictionary)
  t = loader.get_template(template)
  return HttpResponse(t.render(c), mimetype=mimetype)
Пример #21
0
 def process_request(self, request):
     locale, path = self.split_locale_from_request(request)
     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:
         #locale = settings.LANGUAGE_CODE
     """ Add selected locale to session """                   
     if hasattr(request, 'session'):
         request.session['django_language'] = locale
     else:
         response.set_cookie(settings.LANGUAGE_COOKIE_NAME, locale)  
         
     translation.activate(locale)
     request.LANGUAGE_CODE = translation.get_language()
Пример #22
0
def change_locale(request):
    """
    Redirect to a given url while changing the locale in the path
    The url and the locale code need to be specified in the
    request parameters.
    """
    next = request.REQUEST.get('next', None)
    if not next:
        referrer = request.META.get('HTTP_REFERER', None)
        if referrer:
            next = urlsplit(referrer)[2]
    if not next:
        next = '/'
    _, path = utils.strip_path(next)
    locale = request.REQUEST.get('locale', None)
    if locale and check_for_language(locale):
        if localeurl_settings.USE_SESSION:
            request.session['django_language'] = locale
        path = utils.locale_path(path, locale)

    response = http.HttpResponseRedirect(path)
    return response
 def process_request(self, request):
     locale, path = utils.strip_path(request.path_info)
     if localeurl_settings.USE_ACCEPT_LANGUAGE and not locale:
         accept_langs = filter(lambda x: x, [utils.supported_language(lang[0])
                                             for lang in
                                             parse_accept_lang_header(
                     request.META.get('HTTP_ACCEPT_LANGUAGE', ''))])
         if accept_langs:
             locale = accept_langs[0]
     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 HttpResponsePermanentRedirect(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()
Пример #24
0
def change_locale(request):
    """
    Redirect to a given url while changing the locale in the path
    The url and the locale code need to be specified in the
    request parameters.
    """
    next = request.REQUEST.get("next", None)
    if not next:
        referrer = request.META.get("HTTP_REFERER", None)
        if referrer:
            next = urlsplit(referrer)[2]
    if not next:
        next = "/"
    _, path = utils.strip_path(next)
    if request.method == "POST":
        locale = request.POST.get("locale", None)
        if locale and check_for_language(locale):
            if localeurl_settings.USE_SESSION:
                request.session["django_language"] = locale
            path = utils.locale_path(path, locale)
            signals.locale_change.send(sender=change_locale, locale=locale, user=request.user)

    response = http.HttpResponseRedirect(path)
    return response
Пример #25
0
 def process_request(self, request):
     
     #  we check if another middleware has already set the language, eg. from domain name
     if not hasattr(request, "LANGUAGE_CODE") or not request.LANGUAGE_CODE: 
         
         locale, path = utils.strip_path(request.path_info)
          
         #return HttpResponse(str((request.META["SCRIPT_NAME"], request.path_info, locale)))
         
         if localeurl_settings.USE_ACCEPT_LANGUAGE and not locale:
             accept_langs = filter(lambda x: x, 
                                   [utils.supported_language(lang[0])
                                    for lang in parse_accept_lang_header(
                                    request.META.get('HTTP_ACCEPT_LANGUAGE', ''))])
             if accept_langs:
                 locale = accept_langs[0]
         locale_path = utils.locale_path(path, locale)
     
         if locale_path != request.path_info:
             
             full_path = ''.join([request.META["SCRIPT_NAME"], locale_path])
                                       
             query = request.META.get("QUERY_STRING", "")
             if query:
                 full_path = "%s?%s" % (full_path, query)
                 
             return HttpResponsePermanentRedirect(full_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 = locale
Пример #26
0
 def change_language_in_path(path, language):
     locale,path = utils.strip_path(path)
     if locale:
         return utils.locale_path(path, language)
     else:
         return path