Example #1
0
    def post(request):
        """
        Set a cookie to switch language of web site. Tutorial how to set language cookie at
        https://samulinatri.com/blog/django-translation/

        :param request:
        :type request:
        :return:
        :rtype:
        """
        lang = translation.get_language()
        logger.debug('current language: {}'.format(lang))
        logger.debug('check_for_language: de {}, en-us {}, en-gb {}'.format(
            translation.check_for_language('de'),
            translation.check_for_language('en-us'),
            translation.check_for_language('en-gb')))
        if lang == 'en-gb' or lang == 'en-us':
            translation.activate('de')
            request.session[translation.LANGUAGE_SESSION_KEY] = 'de'
        else:
            translation.activate('en-gb')
            if hasattr(request, 'session'):
                request.session[translation.LANGUAGE_SESSION_KEY] = 'en-gb'
        logger.debug('new language: {}'.format(translation.get_language()))
        logger.debug('translation test: {}'.format(
            translation.gettext("help")))
        response = redirect(DEMO_VAR + '/')
        response.set_cookie(settings.LANGUAGE_COOKIE_NAME,
                            request.session[translation.LANGUAGE_SESSION_KEY])
        return response
    def post(request):
        """

        :param request:
        :type request:
        :return:
        :rtype:
        """
        lang = translation.get_language()
        logger.debug('current language: {}'.format(lang))
        logger.debug('check_for_language: de {}, en-us {}, en-gb {}'.format(
            translation.check_for_language('de'),
            translation.check_for_language('en-us'),
            translation.check_for_language('en-gb')))
        if lang == 'en-gb' or lang == 'en-us':
            translation.activate('de')
            request.session[translation.LANGUAGE_SESSION_KEY] = 'de'
        else:
            translation.activate('en-gb')
            if hasattr(request, 'session'):
                request.session[translation.LANGUAGE_SESSION_KEY] = 'en-gb'
        logger.debug('new language: {}'.format(translation.get_language()))
        logger.debug('translation test: {}'.format(
            translation.gettext("help")))
        return redirect('/')
 def process_request(self, request):
     
     from django.utils import translation
             
     path_tuple = request.path_info.split("/")
     
     if len(path_tuple) > 1:
         
         if path_tuple[1] in settings.NOT_LANG_URLS:
             return
     
         if check_for_language(path_tuple[1]):
             
             lang = path_tuple[1]
             
             if hasattr(request, 'session'):
                 request.session['django_language'] = lang
             
             request.COOKIES['django_language'] = lang
         
             set_default_language(lang)
             request.path_info = "/" + "/".join(path_tuple[2:])                
             return
     
     if hasattr(request, "session") and "django_language" in request.session:
         lang = request.session["django_language"]
     elif hasattr(request, "COOKIE") and "django_language" in request.COOKIE:
         lang = request.COOKIE["django_language"]
     elif check_for_language(get_language_from_request(request)):
         set_default_language(get_language_from_request(request))
         lang = get_language_from_request(request)
     else:
         lang = settings.LANGUAGES[settings.DEFAULT_LANGUAGE][0]
         
     return HttpResponseRedirect('/%s%s' % (lang, request.path_info))
Example #4
0
def get_language_from_request(request):
    global _accepted
    from django.conf import settings

    supported = dict(settings.LANGUAGES)

    # If a previous midleware has decided the language use it
    if hasattr(request, "LANGUAGE_CODE"):
        lang_code = request.LANGUAGE_CODE
        if lang_code in supported and lang_code is not None and translation.check_for_language(lang_code):
            return lang_code

    if hasattr(request, "session"):
        lang_code = request.session.get("django_language", None)
        if lang_code in supported and lang_code is not None and translation.check_for_language(lang_code):
            return lang_code

    lang_code = request.COOKIES.get("django_language")

    if lang_code and lang_code in supported and translation.check_for_language(lang_code):
        return lang_code

    take_browser_prefs = getattr(settings, "USE_BROWSER_LANGUAGE_PREFS", True)
    if take_browser_prefs:
        # try get it from browser preferences
        browser_pref_langs = get_browser_languages(request)
        for lang_code in browser_pref_langs:
            if lang_code in supported and translation.check_for_language(lang_code):
                return lang_code

    # Initially use the default language
    return settings.LANGUAGE_CODE
Example #5
0
File: i18n.py Project: laoyin/nyf
def javascript_catalog(request, domain='djangojs', packages=None):
    """
    Returns the selected language catalog as a javascript library.

    Receives the list of packages to check for translations in the
    packages parameter either from an infodict or as a +-delimited
    string from the request. Default is 'django.conf'.

    Additionally you can override the gettext domain for this view,
    but usually you don't want to do that, as JavaScript messages
    go to the djangojs domain. But this might be needed if you
    deliver your JavaScript source from Django templates.
    """
    locale = to_locale(get_language())

    if request.session and 'django_language' in request.session:
        if check_for_language(request.session['django_language']):
            locale = to_locale(request.session['django_language'])

    if request.GET and 'language' in request.GET:
        if check_for_language(request.GET['language']):
            locale = to_locale(request.GET['language'])

    if packages is None:
        packages = ['django.conf']
    if isinstance(packages, six.string_types):
        packages = packages.split('+')

    catalog, plural = get_javascript_catalog(locale, domain, packages)
    return render_javascript_catalog(catalog, plural)
Example #6
0
def change_language(request):
    """
    Redirect to a new hostname when the user wishes for a language change.
    The user will be redirected to the same page he was before.

    """
    if request.method == 'POST':
        hostname = request.get_host().split(':')[0]
        previous_page = request.POST.get('previous-page', '/')

        # The News category may have articles available only for certain
        # languages, so we redirect to the News index instead.
        # BAD: the urls are coded in code, rather than to the sole knowledge
        #      of the urls.py definition.
        news_url = re.match(r"^/news/.*$", previous_page)
        if news_url:
            previous_page = '/news/'
        news_url = re.match(r"^/blogs/.*$", previous_page)
        if news_url:
            previous_page = '/blogs/'
        news_url = re.match(r"^/blogarticle/.*$", previous_page)
        if news_url:
            previous_page = '/blogarticle/'
        news_url = re.match(r"^/article/.*$", previous_page)
        if news_url:
            previous_page = '/article/'

        new_language = request.POST.get('language')
        if new_language and translation.check_for_language(new_language):
            url_regex = re.compile("^(?P<protocol>http[s]?://).*$")
            uri = request.build_absolute_uri()
            protocol = url_regex.match(uri).group('protocol')

            # If the previous language is in the host remove it.
            # Also if the hostname starts with 'www.' (may appear in the
            # default language site) remove it so that the language prefix gets
            # applied to the domain name.
            previous_language = hostname.split('.', 1)[0]
            if (translation.check_for_language(previous_language)
                    or previous_language == 'www'):
                no_language_host = request.get_host().replace(
                    previous_language + '.', '', 1)
            else:
                no_language_host = request.get_host()

            language_prefix = new_language + '.'
            response = HttpResponseRedirect(protocol + language_prefix +
                                            no_language_host + previous_page)
        else:
            response = HttpResponseRedirect(previous_page)

        return response
    return HttpResponseRedirect('/')
Example #7
0
File: views.py Project: stnb/stnb
def set_language(request):
    """
    Redirect to a given url while setting the chosen language in the
    session or cookie. The url and the language code need to be
    specified in the request parameters.

    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    redirect to the page in the request (the 'next' parameter) without changing
    any state.
    """
    next = request.REQUEST.get("next", None)
    if not next:
        next = request.META.get("HTTP_REFERER", None)
    if not next:
        next = "/"

    old_lang = get_language()
    lang_code = request.GET.get("language", None)
    if lang_code and check_for_language(lang_code):
        if hasattr(request, "session"):
            request.session["django_language"] = lang_code
        else:
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
        path = urlparse(next).path
        if path[0 : len(old_lang) + 2] == "/%s/" % old_lang:
            next = re.sub(path, "/%s/" % lang_code + path[len(old_lang) + 2 :], next)
            path = "/%s/" % lang_code + path[len(old_lang) + 2 :]
    response = http.HttpResponseRedirect(next)

    return response
Example #8
0
    def GET(self):
        lang_code = self.param('language')
        next = self.param('next')
        if (not next) and os.environ.has_key('HTTP_REFERER'):
            next = os.environ['HTTP_REFERER']
        if not next:
            next = '/'
        #os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
        from django.utils.translation import check_for_language, activate, to_locale, get_language
        #from django.conf import settings
        #settings._target = None

        if lang_code and check_for_language(lang_code):
            self.blog.language=lang_code
            
            ## set settings lang code, and session cookie
            settings.LANGUAGE_CODE = lang_code
            if hasattr(self.request, 'session'):
                self.request.session['django_language'] = lang_code
            #max_age =  60*60*24*365
            #expires = datetime.strftime(datetime.utcnow() + timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT")
            #self.response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code, max_age, expires)
    
            #activate(self.blog.language)
            self.blog.save()
        self.redirect(next)
Example #9
0
    def handle(self, request, data):
        response = shortcuts.redirect(request.build_absolute_uri())
        print "this is settings data:  : '%s'" % data['language']
        print "this is settings user_id :::: '%s'" % request.user.id
        print "this is settings response::::'%s'" % response
        # Language
        lang_code = data['language']
        if lang_code and translation.check_for_language(lang_code):
            if hasattr(request, 'session'):
                request.session['django_language'] = lang_code
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME,
                                lang_code,
                                expires=_one_year())

        # Timezone
        request.session['django_timezone'] = pytz.timezone(
            data['timezone']).zone
        response.set_cookie('django_timezone',
                            data['timezone'],
                            expires=_one_year())

        request.session['horizon_pagesize'] = data['pagesize']
        response.set_cookie('horizon_pagesize',
                            data['pagesize'],
                            expires=_one_year())

        with translation.override(lang_code):
            messages.success(request,
                             encoding.force_unicode(_("Settings saved.")))

        return response
Example #10
0
def translation_set_language(request, select_language):
    """
    Set and activate a language, if that language is available.
    """
    if translation.check_for_language(select_language):
        fallback = False
    else:
        # The page is in a language that Django has no messages for.
        # We display anyhow, but fall back to primary language for
        # other messages and other applications. It is *highly* recommended to
        # create a new django.po for the language instead of
        # using this behaviour.
        select_language = django_settings.LANGUAGES[0][0]
        fallback = True

    translation.activate(select_language)
    request.LANGUAGE_CODE = translation.get_language()

    if hasattr(request, 'session'):
        # User has a session, then set this language there
        if select_language != request.session.get('django_language'):
            request.session['django_language'] = select_language
    elif request.method == 'GET' and not fallback:
        # No session is active. We need to set a cookie for the language
        # so that it persists when the user changes his location to somewhere
        # not under the control of the CMS.
        # Only do this when request method is GET (mainly, do not abort
        # POST requests)
        response = HttpResponseRedirect(request.get_full_path())
        response.set_cookie(django_settings.LANGUAGE_COOKIE_NAME, select_language)
        return response
Example #11
0
 def form_valid(self, form):
     # Create user instance with fixed username
     form.instance.username = create_username(
         form.instance.first_name,
         form.instance.last_name
     )
     form.instance.is_active = False
     form.instance.set_password(form.cleaned_data['password1'])
     form.instance.save()
     # Create token for mobile API
     Token.objects.create(user=form.instance)
     # Create registration link and save along with request params
     salt = hashlib.md5()
     salt.update(settings.SECRET_KEY + str(datetime.datetime.now().time))
     register_demand = RegisterDemand.objects.create(
         activation_link = salt.hexdigest(),
         ip_address = ip.get_ip(self.request),
         user = form.instance,
         email = form.instance.email,
         lang = translation.get_language_from_request(self.request)
     )
     # Create full link to activation page for new user
     site_url = self.request.build_absolute_uri('/user/activate/')
     link = site_url + str(register_demand.activation_link)
     # Send email in user's own language if possible
     email = emails.ActivationLink()
     email_context = {'link': link}
     if translation.check_for_language(register_demand.lang):
         email_context.update({'lang': register_demand.lang})
     email.send(register_demand.email, email_context)
     return render(self.request, 'userspace/register-success.html',
                                     {'title': _("Message send"),})
Example #12
0
def set_language(request, next=None):
    """
    Redirect to a given url while setting the chosen language in the
    session or cookie. The url and the language code need to be
    specified in the request parameters.
    Try to save the new language in the User's profile.
    """

    next = next \
        or request.REQUEST.get('next', None) \
        or request.META.get('HTTP_REFERER', None) \
        or '/'

    response = HttpResponseRedirect(next)
    if request.method == 'GET' or request.method == 'POST':
        lang_code = request.REQUEST.get('language', settings.LANGUAGE_CODE)
        if check_for_language(lang_code):
            # update the language in the url if it's in there
            next = change_language_in_path(next, lang_code)
            response = HttpResponseRedirect(next)

            set_language_on_response(request, response, lang_code)

            # try to save language in the user profile
            if request.user.is_authenticated():
                try:
                    user = request.user
                    user.language = lang_code
                    user.save()
                except:
                    pass

    return response
    def handle(self, request, data):
        response = shortcuts.redirect(request.build_absolute_uri())
        # Language
        lang_code = data['language']
        if lang_code and translation.check_for_language(lang_code):
            if hasattr(request, 'session'):
                request.session['django_language'] = lang_code
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code,
                                expires=_one_year())

        # Timezone
        request.session['django_timezone'] = pytz.timezone(
            data['timezone']).zone
        response.set_cookie('django_timezone', data['timezone'],
                            expires=_one_year())

        request.session['horizon_pagesize'] = data['pagesize']
        response.set_cookie('horizon_pagesize', data['pagesize'],
                            expires=_one_year())

        request.session['instance_log_length'] = data['instance_log_length']
        response.set_cookie('instance_log_length',
                            data['instance_log_length'], expires=_one_year())

        with translation.override(lang_code):
            messages.success(request,
                             encoding.force_text(_("Settings saved.")))

        return response
Example #14
0
def set_language(request, runinfo=None, next=None):
    """
    Change the language, save it to runinfo if provided, and
    redirect to the provided URL (or the last URL).
    Can also be used by a url handler, w/o runinfo & next.
    """
    if not next:
        next = request.REQUEST.get('next', None)
    if not next:
        next = request.META.get('HTTP_REFERER', None)
        if not next:
            next = '/'
    response = HttpResponseRedirect(next)
    response['Expires'] = "Thu, 24 Jan 1980 00:00:00 GMT"
    if request.method == 'GET':
        lang_code = request.GET.get('lang', None)
        if lang_code and translation.check_for_language(lang_code):
            if hasattr(request, 'session'):
                request.session['django_language'] = lang_code
            else:
                response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
            if runinfo:
                runinfo.subject.language = lang_code
                runinfo.subject.save()
    return response
Example #15
0
def javascript_catalog(request, domain='djangojs', packages=None):
    """
Returns the selected language catalog as a javascript library.

Receives the list of packages to check for translations in the
packages parameter either from an infodict or as a +-delimited
string from the request. Default is 'django.conf'.

Additionally you can override the gettext domain for this view,
but usually you don't want to do that, as JavaScript messages
go to the djangojs domain. But this might be needed if you
deliver your JavaScript source from Django templates.
"""
    locale = to_locale(get_language())

    if request.GET and 'language' in request.GET:
        if check_for_language(request.GET['language']):
            locale = to_locale(request.GET['language'])

    if packages is None:
        packages = ['django.conf']
    if isinstance(packages, six.string_types):
        packages = packages.split('+')

    catalog = None
    try:
        catalog, plural = get_javascript_catalog(locale, domain, packages)
    except TranslationError as ex:
        # We know how to handle one specific type of error - so let's do
        # something useful there.
        if re.match(r'.*duplicate message definition', ex.args[0]):
            return render_duplicate_error_js(ex.args[0])

        raise Exception(ex.msg)
    return render_javascript_catalog(catalog, plural)
Example #16
0
    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        if form.is_valid():
            lang_code = request.POST.get('language', None)
            next = request.REQUEST.get('next', None)
            if request.is_ajax():
                response = HttpResponse(json.dumps({'success': True}),
                                        mimetype='application/json')
            else:
                response = HttpResponseRedirect(next)
            if lang_code and check_for_language(lang_code):
                if hasattr(request, 'session'):
                    request.session[settings.LANGUAGE_COOKIE_NAME] = lang_code
                else:
                    response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
            return response

        if request.is_ajax():
            errors = ' '.join(form.non_field_errors())
            for fieldname, errorlist in form.errors.items():
                if fieldname in form.fields:
                    errors += ' ' + form.fields[fieldname].label + ': '
                    errors += ' '.join(errorlist)
                else:
                    errors += ' '.join(errorlist)
            return HttpResponse(json.dumps({'success': False,
                                            'error_message': errors}),
                                mimetype='application/json')
        return self.form_invalid(form)
Example #17
0
def set_language(request):

    """
    Set_language view from Django.
    Redirect to a given url while setting the chosen language in the
    session or cookie. The url and the language code need to be
    specified in the request parameters.
    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    redirect to the page in the request (the 'next' parameter) without changing
    any state.
    """

    next = request.POST.get('next', request.GET.get('next'))
    if not is_safe_url(url=next, host=request.get_host()):
        next = request.META.get('HTTP_REFERER')
        if not is_safe_url(url=next, host=request.get_host()):
            next = '/'
    response = http.HttpResponseRedirect(next)
    if request.method == 'POST':
        lang_code = request.POST.get('language', None)
        try:
            user = get_object_or_404(InoxUser, email=request.user)
            if user.is_authenticated:
                user.lang = lang_code
                user.save()
        except:
            pass
        if lang_code and check_for_language(lang_code):
            if hasattr(request, 'session'):
                request.session['django_language'] = lang_code
            else:
                response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
    return response
Example #18
0
def set_language(request):
    next = request.REQUEST.get("next", None)
    if not next:
        next = "/"

    url = urlparse(next)

    try:
        r = resolve(url.path)
    except:
        next = "/"

    response = http.HttpResponseRedirect(next)
    lang_code = request.GET.get("language", None)

    if lang_code and check_for_language(lang_code):
        translation.activate(lang_code)
        try:
            next = reverse("%s" % r.url_name, args=r.args, kwargs=r.kwargs)
        except:
            pass
        else:
            response = http.HttpResponseRedirect(next)
        translation.deactivate()

        if hasattr(request, "session"):
            request.session["django_language"] = lang_code
        else:
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)

    return response
Example #19
0
def set_language(request, language):
    """
    Change the language of session of authenticated user.
    """

    if check_for_language(language):
        request.session['django_language'] = language
def set_language(request):
    """
    Redirect to a given url while setting the chosen language in the user
    setting. The url and the language code need to be specified in the request
    parameters.

    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    redirect to the page in the request (the 'next' parameter) without changing
    any state.
    """

    next = request.REQUEST.get('next', None)
    if not next:
        next = request.META.get('HTTP_REFERER', None)
    if not next:
        next = '/'
    response = http.HttpResponseRedirect(next)
    if request.method == 'POST':
        lang_code = request.POST.get('language', None)
        if lang_code and translation.check_for_language(lang_code):
            # We reload to make sure user object is recent
            request.user.reload()
            request.user.language = lang_code
            request.user.save()
    return response
Example #21
0
def set_language(request):
    """
    Redirect to a given url while setting the chosen language in the
    session or cookie. The url and the language code need to be
    specified in the request parameters.
    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    redirect to the page in the request (the 'next' parameter) without changing
    any state.
    """
    next = request.POST.get('next', request.GET.get('next'))
    if not is_safe_url(url=next, host=request.get_host()):
        next = request.META.get('HTTP_REFERER')
        if not is_safe_url(url=next, host=request.get_host()):
            next = '/'
    response = http.HttpResponseRedirect(next)
    if request.method == 'POST':
        lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER)
        if lang_code and check_for_language(lang_code):
            next_trans = translate_url(next, lang_code)
            if next_trans != next:
                response = http.HttpResponseRedirect(next_trans)
            if hasattr(request, 'session'):
                request.session[LANGUAGE_SESSION_KEY] = lang_code
            # Always set cookie
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code,
                                max_age=settings.LANGUAGE_COOKIE_AGE,
                                path=settings.LANGUAGE_COOKIE_PATH,
                                domain=settings.LANGUAGE_COOKIE_DOMAIN)
    return response
Example #22
0
def set_language(request, next=None):
    '''
    Redirect to a given url while setting the chosen language in the
    session or cookie. The url and the language code need to be
    specified in the request parameters.
    Try to save the new language in the User's profile.
    '''
    next = next \
        or get_from_request(request, 'next', None) \
        or request.META.get('HTTP_REFERER', None) \
        or '/'

    response = HttpResponseRedirect(next)
    if request.method == 'GET' or request.method == 'POST':
        lang_code = get_from_request(request, 'language', settings.LANGUAGE_CODE)
        if check_for_language(lang_code):
            # update the language in the url if it's in there
            next = change_language_in_path(next, lang_code)
            response = HttpResponseRedirect(next)

            set_language_on_response(request, response, lang_code)

            # Try to save language in the user profile,
            # unless a staff user is logged in as that user (via django-token-auth)
            if request.user.is_authenticated() and not request.session.get('token_auth_impersonating', False):
                try:
                    p = request.user.get_profile()
                    p.language = lang_code
                    p.save()
                except:
                    pass

    return response
Example #23
0
def set_lang(request, new_lang, old_lang=None):
    # old_langg     = get_language_from_request(request, check_path=True)
    # old_langg     = get_language()
    default_lang = settings.LANGUAGE_CODE
    splitted = request.META['HTTP_REFERER'].split('/')
    old_lang = default_lang
    if check_for_language(splitted[3]):
        old_lang = splitted[3]
    if new_lang == old_lang and new_lang == default_lang:
        print('1')
    elif new_lang == old_lang and new_lang != default_lang:
        print('2')
        splitted[3] = new_lang
    elif new_lang != old_lang and new_lang != default_lang:
        print('3')
        print(splitted)
        if old_lang == default_lang:
            splitted.insert(3, new_lang)
        else:
            splitted[3] = new_lang
    elif new_lang != old_lang and new_lang == default_lang:
        print('4')
        del splitted[3]
    elif new_lang != old_lang and new_lang != default_lang:
        print('5')
        splitted.insert(3, new_lang)
    translation.activate(new_lang)
    request.session[translation.LANGUAGE_SESSION_KEY] = new_lang
    return redirect('/'.join(splitted))
Example #24
0
def local_login(request, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    login
    """
    redirect_to = request.REQUEST.get(redirect_field_name, '')
    if request.method == 'POST':
        lang_code = request.POST.get('language', None)
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL
            login(request, form.get_user())
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
            set_user_addresses(request)
            if lang_code and check_for_language(lang_code):
                request.session['django_language'] = lang_code
            # load default filter
            if getattr(settings, 'LOAD_BARUWA_DEFAULT_FILTER', None):
                aday = datetime.timedelta(days=1)
                yesterday = datetime.date.today() - aday
                fitem = dict(field='date', filter=3, value=yesterday)
                if not 'filter_by' in request.session:
                    request.session['filter_by'] = []
                if not fitem in request.session['filter_by']:
                    request.session['filter_by'].append(fitem)
                    request.session.modified = True
            return HttpResponseRedirect(redirect_to)
    else:
        form = AuthenticationForm(request)
    request.session.set_test_cookie()
    return render_to_response('accounts/login.html',
        {'form': form, redirect_field_name: redirect_to},
        context_instance=RequestContext(request))
Example #25
0
def iter_format_modules(lang, format_module_path=None):
    """Find format modules."""
    if not check_for_language(lang):
        return

    if format_module_path is None:
        format_module_path = settings.FORMAT_MODULE_PATH

    format_locations = []
    if format_module_path:
        if isinstance(format_module_path, str):
            format_module_path = [format_module_path]
        for path in format_module_path:
            format_locations.append(path + ".%s")
    format_locations.append("django.conf.locale.%s")
    locale = to_locale(lang)
    locales = [locale]
    if "_" in locale:
        locales.append(locale.split("_")[0])
    for location in format_locations:
        for loc in locales:
            try:
                yield import_module("%s.formats" % (location % loc))
            except ImportError:
                pass
Example #26
0
    def process_request(self, request):
        """ 
        This builds strongly on django's Locale middleware, so check 
        if it's enabled.

        This middleware is only relevant with i18n_patterns.
        """

        if self.enable_middleware():
            if request.user.is_authenticated():
                lang_code = request.user.primary_language

                if lang_code:
                    # Early redirect based on language to prevent Ember from finding out and redirect after loading a complete page in the wrong language.
                    expected_url_lang_prefix = '/{0}/'.format(lang_code)
                    url_parts = request.path.split('/')
                    if len(url_parts) >= 2:
                        current_url_lang_prefix = url_parts[1]
                        if current_url_lang_prefix in dict(settings.LANGUAGES).keys() and not request.path.startswith(expected_url_lang_prefix):
                            new_location = request.get_full_path().replace('/{0}/'.format(current_url_lang_prefix), expected_url_lang_prefix)
                            return http.HttpResponseRedirect(new_location)
                    # End early redirect.
                
                    if translation.check_for_language(lang_code):
                        # activate the language
                        translation.activate(lang_code)
                        request.LANGUAGE_CODE = translation.get_language()
            else:
                pass #TODO
Example #27
0
 def set_language(self, code, response=None):
     if not (self._check_for_language(code) and check_for_language(code)):
         raise Exception(_("Given language code ({}) is not correct!".format(code)))
     self.browser_store_manager.set(self.SESSION_APP_LANGUAGE_KEY, code, response=response)
     self.browser_store_manager.set(LANGUAGE_SESSION_KEY, code, response=response)
     self.client.language = code
     self.client.language_obj = DataController.get_language(code)
Example #28
0
    def handle(self, request, data):
        response = shortcuts.redirect(request.build_absolute_uri())

        lang_code = data['language']
        if lang_code and translation.check_for_language(lang_code):
            response = functions.save_config_value(
                request, response, settings.LANGUAGE_COOKIE_NAME, lang_code)

        response = functions.save_config_value(
            request, response, 'django_timezone',
            pytz.timezone(data['timezone']).zone)

        response = functions.save_config_value(request, response,
                                               'API_RESULT_PAGE_SIZE',
                                               data['pagesize'])

        response = functions.save_config_value(request, response,
                                               'INSTANCE_LOG_LENGTH',
                                               data['instance_log_length'])

        with translation.override(lang_code):
            messages.success(request,
                             encoding.force_text(_("Settings saved.")))

        return response
Example #29
0
def set_language(request):
    """
    Redirect to a given url while setting the chosen language in the
    session or cookie. The url and the language code need to be
    specified in the request parameters.

    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    redirect to the page in the request (the 'next' parameter) without changing
    any state.
    """
    next = request.POST.get('next', request.GET.get('next'))
    if not is_safe_url(url=next, host=request.get_host()):
        next = request.META.get('HTTP_REFERER')
        if not is_safe_url(url=next, host=request.get_host()):
            next = '/'
    response = http.HttpResponseRedirect(next)
    if request.method == 'POST':
        lang_code = request.POST.get('language', None)
        if lang_code and check_for_language(lang_code):
            next_trans = translate_url(next, lang_code)
            if next_trans != next:
                response = http.HttpResponseRedirect(next_trans)
            if hasattr(request, 'session'):
                request.session[LANGUAGE_SESSION_KEY] = lang_code
            else:
                response.set_cookie(settings.LANGUAGE_COOKIE_NAME,
                                    lang_code,
                                    max_age=settings.LANGUAGE_COOKIE_AGE,
                                    path=settings.LANGUAGE_COOKIE_PATH,
                                    domain=settings.LANGUAGE_COOKIE_DOMAIN)
    return response
Example #30
0
def get_supported_language_variant(lang_code, strict=False):
    """
    Returns the language-code that's listed in supported languages, possibly
    selecting a more generic variant. Raises LookupError if nothing found.
    If `strict` is False (the default), the function will look for an alternative
    country-specific variant when the currently checked is not found.
    lru_cache should have a maxsize to prevent from memory exhaustion attacks,
    as the provided language codes are taken from the HTTP request. See also
    <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>.
    """
    if lang_code:
        # If 'fr-ca' is not supported, try special fallback or language-only 'fr'.
        possible_lang_codes = [lang_code]
        try:
            # TODO skip this, or import updated LANG_INFO format from __future__
            # (fallback option wasn't added until
            # https://github.com/django/django/commit/5dcdbe95c749d36072f527e120a8cb463199ae0d)
            possible_lang_codes.extend(LANG_INFO[lang_code]['fallback'])
        except KeyError:
            pass
        generic_lang_code = lang_code.split('-')[0]
        possible_lang_codes.append(generic_lang_code)
        supported_lang_codes = dict(settings.LANGUAGES)

        for code in possible_lang_codes:
            # Note: django 1.4 implementation of check_for_language is OK to use
            if code in supported_lang_codes and translation.check_for_language(
                    code):
                return code
        if not strict:
            # if fr-fr is not supported, try fr-ca.
            for supported_code in supported_lang_codes:
                if supported_code.startswith(generic_lang_code + '-'):
                    return supported_code
    raise LookupError(lang_code)
Example #31
0
def iter_format_modules(lang, format_module_path=None):
    """
    Does the heavy lifting of finding format modules.
    """
    if not check_for_language(lang):
        return

    if format_module_path is None:
        format_module_path = settings.FORMAT_MODULE_PATH

    format_locations = []
    if format_module_path:
        if isinstance(format_module_path, six.string_types):
            format_module_path = [format_module_path]
        for path in format_module_path:
            format_locations.append(path + '.%s')
    format_locations.append('django.conf.locale.%s')
    locale = to_locale(lang)
    locales = [locale]
    if '_' in locale:
        locales.append(locale.split('_')[0])
    for location in format_locations:
        for loc in locales:
            try:
                yield import_module('%s.formats' % (location % loc))
            except ImportError:
                pass
Example #32
0
def change_language(request):
    _next = request.REQUEST.get('next', None)
    if not _next:
        _next = request.META.get('HTTP_REFERER', None)

    if not _next:
        _next = '/'

    # если уже есть языковой префикс URL, надо убрать его
    for supported_language in settings.LANGUAGES:
        prefix = '/%s/' % supported_language[0]
        if _next.startswith(prefix):
            _next = _next[len(prefix):]
            break

    language = request.REQUEST.get(u'language', None)
    if language and check_for_language(language):
        if _next == '/':
            # response = HttpResponseRedirect('/')
            response = HttpResponseRedirect('/%s/' % language)
        else:
            response = HttpResponseRedirect('/%s/%s' % (language, _next))

        if hasattr(request, 'session'):
            request.session['django_language'] = language
        else:
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language)

        translation.activate(language)
        return response
    else:
        return HttpResponse(status=400)
Example #33
0
def prepare_email_content(template, context, tz, language='en'):
    if not translation.check_for_language(language):
        language = 'en'

    with timezone.override(tz), translation.override(language):

        html_content = None

        try:
            html_template = get_template('{}.html.jinja2'.format(template))
            html_content = html_template.render(context)
        except TemplateDoesNotExist:
            pass

        try:
            text_template = get_template('{}.text.jinja2'.format(template))
            text_content = text_template.render(context)
        except TemplateDoesNotExist:
            if html_content:
                text_content = generate_plaintext_from_html(html_content)
            else:
                raise Exception(
                    'Nothing to use for text content, no text or html templates available.'
                )

        subject = render_to_string('{}.subject.jinja2'.format(template),
                                   context).replace('\n', '')

        return subject, text_content, html_content
Example #34
0
def lang(request, lang_code):
    next = request.POST.get('next', request.GET.get('next'))
    if (next or not request.is_ajax()) and not is_safe_url(
            url=next, host=request.get_host()):
        next = request.META.get('HTTP_REFERER')
        if next:
            next = urlunquote(next)  # HTTP_REFERER may be encoded.
        if not is_safe_url(url=next, host=request.get_host()):
            next = '/'
    response = HttpResponseRedirect(next) if next else HttpResponse(status=204)

    if lang_code and check_for_language(lang_code):
        if next:
            # Ниже идёт пояснение MySettings.LANGUAGES
            for code_tuple in MySettings.LANGUAGES:
                settings_lang_code = "/" + code_tuple[0]
                parsed = urlsplit(next)
                if parsed.path.startswith(settings_lang_code):
                    path = re.sub('^' + settings_lang_code, '', parsed.path)
                    next = urlunsplit((parsed.scheme, parsed.netloc, path,
                                       parsed.query, parsed.fragment))
            response = HttpResponseRedirect(next)
        if hasattr(request, 'session'):
            request.session[LANGUAGE_SESSION_KEY] = lang_code
        else:
            response.set_cookie(
                settings.LANGUAGE_COOKIE_NAME,
                lang_code,
                max_age=settings.LANGUAGE_COOKIE_AGE,
                path=settings.LANGUAGE_COOKIE_PATH,
                domain=settings.LANGUAGE_COOKIE_DOMAIN,
            )
    return response
Example #35
0
 def validate_language_id(self, language_id):
     """
     Check that the language_id is supported by Kolibri
     """
     if not check_for_language(language_id):
         raise serializers.ValidationError(_("Language is not supported by Kolibri"))
     return language_id
Example #36
0
def set_lang(request):
    next = request.POST.get('next', request.GET.get('next'))
    if ((next or not request.is_ajax())
            and not is_safe_url(url=next,
                                allowed_hosts={request.get_host()},
                                require_https=request.is_secure())):
        next = request.META.get('HTTP_REFERER')
        next = next and unquote(next)  # HTTP_REFERER may be encoded.
        if not is_safe_url(url=next,
                           allowed_hosts={request.get_host()},
                           require_https=request.is_secure()):
            next = '/'
    response = HttpResponseRedirect(next) if next else HttpResponse(status=204)
    if request.method == 'POST':
        lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER)
        if lang_code and check_for_language(lang_code):
            if next:
                next_trans = translate_url(next, lang_code)
                response = HttpResponseRedirect(next_trans + "position")
            if hasattr(request, 'session'):
                request.session[LANGUAGE_SESSION_KEY] = lang_code
            response.set_cookie(
                settings.LANGUAGE_COOKIE_NAME,
                lang_code,
                max_age=settings.LANGUAGE_COOKIE_AGE,
                path=settings.LANGUAGE_COOKIE_PATH,
                domain=settings.LANGUAGE_COOKIE_DOMAIN,
            )
    return response
Example #37
0
def changelang(request, code=False, category=False, goasubcategory=False):
	if code and check_for_language(code):
		request.session[LANGUAGE_SESSION_KEY] = code
		activate(code)
	if category and goasubcategory:
		return redirect(reverse('categoryandsub', kwargs={'goacategory':category, 'goasubcategory':goasubcategory}))
	elif category:
		return redirect(reverse('onlycategory', kwargs={'goacategory':category}))
	else:
		returned = request.META.get('HTTP_REFERER', False)
		if returned:
			if 'showbookmark' in returned:
				return redirect(reverse('showbookmark'))
			elif 'classifieds' in returned:
				return redirect(reverse('onlyclassifieds'))
			elif 'addclassified' in returned:
				return redirect(reverse('addclassif'))
			elif 'updatepassword' in returned:
				return redirect(reverse('updatepassword', args=[request.user]))
			elif 'updateuser' in returned:
				return redirect(reverse('updateuser', args=[request.user]))
			elif 'userpage' in returned:
				return redirect(reverse('userpage', args=[request.user]))
			elif 'login' in returned:
				return redirect(reverse('goalogin'))
			elif 'remind-password' in returned:
				return redirect(reverse('remind-password'))
			else:
				return redirect('/')
		else:
			return redirect('/')
Example #38
0
def set_language(request):
    next = None
    if request.method == 'GET':
        next = request.GET.get('next', None)
    elif request.method == 'POST':
        next = request.POST.get('next', None)

    if not next:
        next = request.META.get('HTTP_REFERER', None)
    if not next:
        next = '/'
    response = HttpResponseRedirect(next)

    if request.method == 'GET':
        lang_code = request.GET.get('language', None)
        if lang_code and check_for_language(lang_code):
            if hasattr(request, 'session'):
                request.session["blueking_language"] = lang_code
            max_age = 60 * 60 * 24 * 365
            expires = datetime.datetime.strftime(
                datetime.datetime.utcnow() +
                datetime.timedelta(seconds=max_age),
                "%a, %d-%b-%Y %H:%M:%S GMT")
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code,
                                max_age, expires)
    return response
Example #39
0
    def set_language(self, request):
        """
        Redirect to a given url while setting the chosen language in the
        session or cookie. The url and the language code need to be
        specified in the request parameters.

        Since this view changes how the user will see the rest of the site, it must
        only be accessed as a POST request. If called as a GET request, it will
        redirect to the page in the request (the 'next' parameter) without changing
        any state.
        """
        from django.conf import settings as lazy_settings

        response = Response({'success': True}, status=status.HTTP_200_OK)

        lang_code = request.data['language']
        if lang_code and check_for_language(lang_code):
            if hasattr(request, 'session'):
                request.session[LANGUAGE_SESSION_KEY] = lang_code
            else:
                response.set_cookie(
                    lazy_settings.LANGUAGE_COOKIE_NAME,
                    lang_code,
                    max_age=lazy_settings.LANGUAGE_COOKIE_AGE,
                    path=lazy_settings.LANGUAGE_COOKIE_PATH,
                    domain=lazy_settings.LANGUAGE_COOKIE_DOMAIN)
        return response
Example #40
0
    def process_response(self, request, response):
        if request.method == 'POST':
            language = request.POST.get('language')
            action = request.POST.get('action')
            if action == 'set_language' and check_for_language(language):
                host = request.get_host()
                next_url = request.GET.get('next', None)
                referer = request.META.get('HTTP_REFERER', None)

                if next_url:
                    if is_safe_url(url = next_url, host = host):
                        response = HttpResponseRedirect(next_url)
                elif referer:
                    if is_safe_url(url = referer, host = host):
                        referer_url = urlparse(referer)[2]
                        try:
                            # http://wenda.soso.io/questions/275666/django-templates-get-current-url-in-another-language
                            view = resolve(referer_url)
                            with translation.override(language):
                                next_url = reverse(view.view_name, args = view.args, kwargs = view.kwargs)
                                response = HttpResponseRedirect(next_url)
                        except (Resolver404, NoReverseMatch):
                            pass

                if hasattr(request, 'session'):
                    request.session[translation.LANGUAGE_SESSION_KEY] = language
                else:
                    response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language, max_age = settings.LANGUAGE_COOKIE_AGE, path = settings.LANGUAGE_COOKIE_PATH, domain = settings.LANGUAGE_COOKIE_DOMAIN)

        return response
Example #41
0
def set_language(request):
    """
    It does everything in the django set_language, plus assigning language
    to request.user.profile.

    Below is the behavior of django set_languate:

    Redirect to a given url while setting the chosen language in the
    session or cookie. The url and the language code need to be
    specified in the request parameters.

    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    redirect to the page in the request (the 'next' parameter) without changing
    any state.
    """
    if not settings.USE_I18N:
        raise Http404
    response = dj_set_language(request)
    if request.method == 'POST':
        lang_code = request.POST.get('language', None)
        if lang_code and check_for_language(lang_code):
            profile = request.user.profile
            profile.language = lang_code
            profile.save()
    return response
Example #42
0
def index(request, sitemaps,
          template_name='sitemap_index.xml', content_type='application/xml',
          sitemap_url_name='civmaps.views.sitemap'):

    req_protocol = request.scheme
    req_site = get_current_site(request)

    code = request.META.get('HTTP_HOST', '').split('.')[0]
    if translation.check_for_language(code):
        code = code + '.'
    else:
        code = ''

    sites = []
    for section, site in sitemaps.items():
        if callable(site):
            site = site()
        protocol = req_protocol if site.protocol is None else site.protocol
        sitemap_url = urlresolvers.reverse(
            sitemap_url_name, kwargs={'section': section})
        absolute_url = '%s://%s%s%s' % (protocol, code, req_site.domain, sitemap_url)
        sites.append(absolute_url)
        for page in range(2, site.paginator.num_pages + 1):
            sites.append('%s?p=%s' % (absolute_url, page))

    return TemplateResponse(request, template_name, {'sitemaps': sites},
                            content_type=content_type)
Example #43
0
def set_language(request):
    """
    Redirect to a given url while setting the chosen language in the
    session or cookie. The url and the language code need to be
    specified in the request parameters.

    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    redirect to the page in the request (the 'next' parameter) without changing
    any state.
    """
    next = request.REQUEST.get('next', None)
    if not next:
        next = request.META.get('HTTP_REFERER', None)
    if not next:
        next = '/'
    response = http.HttpResponseRedirect(next)
    if request.method == 'POST':
        lang_code = request.POST.get('language', None)
        if lang_code and check_for_language(lang_code):
            if hasattr(request, 'session'):
                request.session['django_language'] = lang_code
            else:
                response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
    return response
Example #44
0
def language_for_user(user):
    language = user.language

    if not translation.check_for_language(language):
        language = 'en'

    return language
Example #45
0
def iter_format_modules(lang, format_module_path=None):
    """
    Does the heavy lifting of finding format modules.
    """
    if not check_for_language(lang):
        return

    if format_module_path is None:
        format_module_path = settings.FORMAT_MODULE_PATH

    format_locations = []
    if format_module_path:
        if isinstance(format_module_path, six.string_types):
            format_module_path = [format_module_path]
        for path in format_module_path:
            format_locations.append(path + '.%s')
    format_locations.append('django.conf.locale.%s')
    locale = to_locale(lang)
    locales = [locale]
    if '_' in locale:
        locales.append(locale.split('_')[0])
    for location in format_locations:
        for loc in locales:
            try:
                yield import_module('%s.formats' % (location % loc))
            except ImportError:
                pass
Example #46
0
def get_format_modules(reverse=False):
    """
    Returns an iterator over the format modules found in the project and Django
    """
    modules = []
    if not check_for_language(get_language()) or not settings.USE_L10N:
        return modules
    locale = to_locale(get_language())
    if settings.FORMAT_MODULE_PATH:
        format_locations = [settings.FORMAT_MODULE_PATH + '.%s']
    else:
        format_locations = []
    format_locations.append('django.conf.locale.%s')
    for location in format_locations:
        for l in (locale, locale.split('_')[0]):
            try:
                mod = import_module('.formats', location % l)
            except ImportError:
                pass
            else:
                # Don't return duplicates
                if mod not in modules:
                    modules.append(mod)
    if reverse:
        modules.reverse()
    return modules
Example #47
0
def set_language(request, language):
    """
    Change the language of session of authenticated user.
    """

    if check_for_language(language):
        request.session['django_language'] = language
Example #48
0
def setlang_custom(request):
    """
    In this React app, I'm using fetch API to do AJAX requests, and in this particular case
    I have to use a custom i18n function because:
    - For some reason I can't make 'request.POST.get(LANGUAGE_QUERY_PARAMETER)' work with fetch
    - I need to set the 'django_language' cookie, even if I have a session.

    This code is based on set_language():
    https://github.com/django/django/blob/stable/1.10.x/django/views/i18n.py#L28
    """
    lang_code = request.GET.get('lang')
    current_page = request.META.get('HTTP_REFERER')
    log.debug(lang_code)
    log.debug(current_page)
    response = HttpResponseRedirect(current_page)
    if check_for_language(lang_code):
        # I need both session...
        request.session[LANGUAGE_SESSION_KEY] = lang_code
        # AND cookies !
        response.set_cookie(settings.LANGUAGE_COOKIE_NAME,
                            lang_code,
                            max_age=settings.LANGUAGE_COOKIE_AGE,
                            path=settings.LANGUAGE_COOKIE_PATH,
                            domain=settings.LANGUAGE_COOKIE_DOMAIN)

    return response
Example #49
0
def set_language(request):
    """
    Redirect to a given url while setting the chosen language in the
    session or cookie. The url and the language code need to be
    specified in the request parameters.

    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    redirect to the page in the request (the 'next' parameter) without changing
    any state.
    """
    next = request.REQUEST.get('next', None)
    if not next:
        next = request.META.get('HTTP_REFERER', None)
    if not next:
        next = '/'
    response = http.HttpResponseRedirect(next)
    if request.method == 'POST':
        lang_code = request.POST.get('language', None)
        if lang_code and check_for_language(lang_code):
            if hasattr(request, 'session'):
                request.session['django_language'] = lang_code
            else:
                response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
    return response
Example #50
0
 def __setitem__(self, item, value):
     """
             修改一个系统配置项的值到用户个性化设置中,这主要用于系统运行期保存一些个性化的参数设置。
             """
     if self.__getitem__(item) == value: return
     if item in self._cache: self._cache.pop(item)
     op = threadlocals.get_current_user()
     if op and op.is_anonymous(): op = None
     items = item.split(".", 1)
     opt = Option.objects.get(app_label=items[0], name=items[1])
     try:
         p_opt = PersonalOption.objects.get(option=opt, user=op)
     except ObjectDoesNotExist:
         p_opt = PersonalOption(option=opt,
                                user=op)  #create it if not exists
     if not (p_opt.value == value):
         p_opt.value = value
         p_opt.save()
         if item == 'base.language':
             from django.utils.translation import check_for_language, activate, get_language
             request = threadlocals.get_current_request()
             if request:
                 lang_code = value
                 if lang_code and check_for_language(lang_code):
                     if hasattr(request, 'session'):
                         request.session['django_language'] = lang_code
                         activate(lang_code)
                         request.LANGUAGE_CODE = get_language()
     self._cache[item] = value
Example #51
0
def lang(request, code):
    next = request.META.get('HTTP_REFERER', '/')
    response = HttpResponseRedirect(next)
    if code and translation.check_for_language(code):
        request.session[translation.LANGUAGE_SESSION_KEY] = code
        translation.activate(code)
    return response
Example #52
0
def notify_message_push_subscribers_with_language(message, subscriptions,
                                                  language):
    conversation = message.conversation

    if not translation.check_for_language(language):
        language = 'en'

    with translation.override(language):
        message_title = get_message_title(message, language)

    if message.is_thread_reply():
        click_action = frontend_urls.thread_url(message.thread)
    else:
        click_action = frontend_urls.conversation_url(conversation,
                                                      message.author)

    notify_subscribers_by_device(
        subscriptions,
        click_action=click_action,
        fcm_options={
            'message_title': message_title,
            'message_body': Truncator(message.content).chars(num=1000),
            # this causes each notification for a given conversation to replace previous notifications
            # fancier would be to make the new notifications show a summary not just the latest message
            'tag': 'conversation:{}'.format(conversation.id),
        })
Example #53
0
def set_language_ex(request):
    next = request.POST.get('next', request.GET.get('next'))
    if not is_safe_url(url=next, host=request.get_host()):
        next = request.META.get('HTTP_REFERER')
        if not is_safe_url(url=next, host=request.get_host()):
            next = '/'

    # remove lang from query
    scheme, netloc, path, query, fragment = urlparse.urlsplit(next)
    parsed_query = urlparse.parse_qsl(query)
    altered = False
    for k, v in parsed_query[:]:
        if LANG_GET_KEY == k:
            parsed_query.remove((k, v))
            altered = True
    if altered:
        query = urllib.urlencode(parsed_query)
        next = urlparse.urlunsplit((scheme, netloc, path, query, fragment))

    response = http.HttpResponseRedirect(next)
    if request.method == 'POST':
        lang_code = request.POST.get('language', None)
        if lang_code and check_for_language(lang_code):
            if hasattr(request, 'session'):
                request.session[LANGUAGE_SESSION_KEY] = lang_code
            else:
                response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code,
                                    max_age=settings.LANGUAGE_COOKIE_AGE,
                                    path=settings.LANGUAGE_COOKIE_PATH,
                                    domain=settings.LANGUAGE_COOKIE_DOMAIN)
    return response
Example #54
0
def javascript_catalog(request, domain='djangojs', packages=None):
    """
Returns the selected language catalog as a javascript library.

Receives the list of packages to check for translations in the
packages parameter either from an infodict or as a +-delimited
string from the request. Default is 'django.conf'.

Additionally you can override the gettext domain for this view,
but usually you don't want to do that, as JavaScript messages
go to the djangojs domain. But this might be needed if you
deliver your JavaScript source from Django templates.
"""
    locale = to_locale(get_language())

    if request.GET and 'language' in request.GET:
        if check_for_language(request.GET['language']):
            locale = to_locale(request.GET['language'])

    if packages is None:
        packages = ['django.conf']
    if isinstance(packages, six.string_types):
        packages = packages.split('+')

    catalog = None
    try:
        catalog, plural = get_javascript_catalog(locale, domain, packages)
    except TranslationError as ex:
        # We know how to handle one specific type of error - so let's do
        # something useful there.
        if re.match(r'.*duplicate message definition', ex.args[0]):
            return render_duplicate_error_js(ex.args[0])

        raise Exception(ex.msg)
    return render_javascript_catalog(catalog, plural)
Example #55
0
def set_language(request):
    """
    Redirect to a given url while setting the chosen language in the
    session and cookie. The url and the language code need to be
    specified in the request parameters.
    The cookie will have a long expiration date (1 year) for future visits

    Since this view changes how the user will see the rest of the site, it must
    only be accessed as a POST request. If called as a GET request, it will
    redirect to the page in the request (the 'next' parameter) without changing
    any state.
    """
    next = request.GET.get('next', None)
    if not next:
        next = request.POST.get('next', None)
    if not next:
        next = request.META.get('HTTP_REFERER', None)
    if not next:
        next = '/'
    response = http.HttpResponseRedirect(next)
    if request.method == 'POST':
        lang_code = request.POST.get('language', None)
        if lang_code and check_for_language(lang_code):
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code, 365*24*60*60)
    return response
Example #56
0
def get_supported_content_language_variant(lang_code, strict=False):
    """
    Return the language code that's listed in supported languages, possibly
    selecting a more generic variant. Raise LookupError if nothing is found.
    If `strict` is False (the default), look for a country-specific variant
    when neither the language code nor its generic variant is found.
    lru_cache should have a maxsize to prevent from memory exhaustion attacks,
    as the provided language codes are taken from the HTTP request. See also
    <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>.

    This is equvilant to Django's `django.utils.translation.get_supported_content_language_variant`
    but reads the `WAGTAIL_CONTENT_LANGUAGES` setting instead.
    """
    if lang_code:
        # If 'fr-ca' is not supported, try special fallback or language-only 'fr'.
        possible_lang_codes = [lang_code]
        try:
            possible_lang_codes.extend(LANG_INFO[lang_code]["fallback"])
        except KeyError:
            pass
        generic_lang_code = lang_code.split("-")[0]
        possible_lang_codes.append(generic_lang_code)
        supported_lang_codes = get_content_languages()

        for code in possible_lang_codes:
            if code in supported_lang_codes and check_for_language(code):
                return code
        if not strict:
            # if fr-fr is not supported, try fr-ca.
            for supported_code in supported_lang_codes:
                if supported_code.startswith(generic_lang_code + "-"):
                    return supported_code
    raise LookupError(lang_code)
Example #57
0
def set_language(request, runinfo=None, next=None):
    """
    Change the language, save it to runinfo if provided, and
    redirect to the provided URL (or the last URL).
    Can also be used by a url handler, w/o runinfo & next.
    """
    if not next:
        next = request.REQUEST.get('next', None)
    if not next:
        next = request.META.get('HTTP_REFERER', None)
        if not next:
            next = '/'
    response = HttpResponseRedirect(next)
    response['Expires'] = "Thu, 24 Jan 1980 00:00:00 GMT"
    if request.method == 'GET':
        lang_code = request.GET.get('lang', None)
        if lang_code and translation.check_for_language(lang_code):
            if hasattr(request, 'session'):
                request.session['django_language'] = lang_code
            else:
                response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
            if runinfo:
                runinfo.subject.language = lang_code
                runinfo.subject.save()
    return response
Example #58
0
        def get_supported_language_variant(lang_code,
                                           supported=None,
                                           strict=False):
            """
            Returns the language-code that's listed in supported languages, possibly
            selecting a more generic variant. Raises LookupError if nothing found.

            If `strict` is False (the default), the function will look for an alternative
            country-specific variant when the currently checked is not found.
            """
            if supported is None:
                from django.conf import settings

                supported = SortedDict(settings.LANGUAGES)
            if lang_code:
                # if fr-CA is not supported, try fr-ca; if that fails, fallback to fr.
                generic_lang_code = lang_code.split("-")[0]
                variants = (
                    lang_code,
                    lang_code.lower(),
                    generic_lang_code,
                    generic_lang_code.lower(),
                )
                for code in variants:
                    if code in supported and translation.check_for_language(
                            code):
                        return code
                if not strict:
                    # if fr-fr is not supported, try fr-ca.
                    for supported_code in supported:
                        if supported_code.startswith(
                            (generic_lang_code + "-",
                             generic_lang_code.lower() + "-")):
                            return supported_code
            raise LookupError(lang_code)
Example #59
0
def javascript_catalog(request, domain='djangojs', packages=None):
    """
    Returns the selected language catalog as a javascript library.

    Receives the list of packages to check for translations in the
    packages parameter either from an infodict or as a +-delimited
    string from the request. Default is 'django.conf'.

    Additionally you can override the gettext domain for this view,
    but usually you don't want to do that, as JavaScript messages
    go to the djangojs domain. But this might be needed if you
    deliver your JavaScript source from Django templates.
    """
    locale = to_locale(get_language())

    if request.GET and 'language' in request.GET:
        if check_for_language(request.GET['language']):
            locale = to_locale(request.GET['language'])

    if packages is None:
        packages = ['django.conf']
    if isinstance(packages, six.string_types):
        packages = packages.split('+')

    catalog, plural = get_javascript_catalog(locale, domain, packages)
    return render_javascript_catalog(catalog, plural)
Example #60
0
    def get(self, request):
        next = "/"
        if "next" in request.GET:
            next = request.GET.get("next")

        response = HttpResponseRedirect(next)

        if not request.GET:
            return response

        form = forms.LanguageCodeForm(data=request.GET)
        if not form.is_valid():
            return response

        language = form.cleaned_data['language']
        if not translation.check_for_language(language):
            return response

        if hasattr(request, "session"):
            request.session[translation.LANGUAGE_SESSION_KEY] = language
        else:
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language)
        translation.activate(language)

        return response