Beispiel #1
0
 def setUp(self):
     domain = Domain.objects.create(name="test")
     division = Division.objects.create(name="localities", domain=domain)
     self.entity = Entity.objects.create(name="the moon", division=division,
                                         id=settings.QNA_DEFAULT_ENTITY_ID)
     self.common_user = User.objects.create_user("commoner", 
                             "*****@*****.**", "pass")
     self.candidate_user = User.objects.create_user("candidate", 
                             "*****@*****.**", "pass")
     self.candidate_user.profile.locality = self.entity
     self.candidate_user.profile.is_candidate = True
     self.candidate_user.profile.save()
     self.editor_user = User.objects.create_user("editor", 
                             "*****@*****.**", "pass")
     self.editor_user.profile.locality = self.entity
     self.editor_user.profile.is_editor = True
     self.editor_user.profile.save()
     self.q = Question.objects.create(author = self.common_user,
                     subject="why?", entity=self.entity)
     self.a = self.q.answers.create(author = self.candidate_user,
                     content="because the world is round")
     self.site1 = Site.objects.create(domain='abc.com')
     self.site2 = Site.objects.create(domain='fun.com')
     self.q.tags.create(name="abc")
     self.q.tags.create(name="def")
     translation.deactivate_all()
Beispiel #2
0
 def __enter__(self):
     # type: () -> None
     self.old_language = translation.get_language()
     if self.language is not None:
         translation.activate(self.language)
     else:
         translation.deactivate_all()
Beispiel #3
0
def translation(language_code, deactivate=False):
    """
    Port of django.utils.translation.override from Django 1.4

    @param language_code: a language code or ``None``. If ``None``, translation
                          is disabled and raw translation strings are used
    @param    deactivate: If ``True``, when leaving the manager revert to the
                          default behaviour (i.e. ``settings.LANGUAGE_CODE``)
                          rather than the translation that was active prior to
                          entering.
    """
    from django.utils import translation

    original = translation.get_language()
    if language_code is not None:
        translation.activate(language_code)
    else:
        translation.deactivate_all()
    try:
        yield
    finally:
        if deactivate:
            translation.deactivate()
        else:
            translation.activate(original)
Beispiel #4
0
def test_i18n(build_tree, render_template_tag, mock_template_context):

    from sitetree.toolbox import register_i18n_trees

    build_tree(
        {'alias': 'i18tree'},
        [{'title': 'My title', 'url': '/url_default/'}],
    )
    build_tree(
        {'alias': 'i18tree_ru'},
        [{'title': 'Заголовок', 'url': '/url_ru/'}],
    )
    register_i18n_trees(['i18tree'])

    activate('en')
    result = render_template_tag('sitetree', 'sitetree_tree from "i18tree"', mock_template_context())

    assert '/url_default/' in result
    assert 'My title' in result

    activate('ru')
    result = render_template_tag('sitetree', 'sitetree_tree from "i18tree"', mock_template_context())

    assert '/url_ru/' in result
    assert 'Заголовок' in result

    deactivate_all()
Beispiel #5
0
def claiming(request, es=False):
    if es is True:
        activate('es')
    else:
        deactivate_all()
    ages = {}
    for age in AgeChoice.objects.all():
        ages[age.age] = _(age.aside)
    page = Page.objects.get(title='Claiming Social Security')
    tips = {}
    for tooltip in Tooltip.objects.all():
        tips[tooltip.title] = tooltip.text
    questions = {}
    for q in Question.objects.all():
        questions[q.slug] = q
    final_steps = {}
    for step in Step.objects.filter(title__contains='final_'):
        final_steps[step.title] = step
    if standalone:
        base_template = "standalone_base.html"
    else:
        base_template = "%s/templates/base.html" % BASEDIR
    cdict = {
        'tstamp': datetime.datetime.now(),
        'final_steps': final_steps,
        'questions': questions,
        'tips': tips,
        'ages': ages,
        'page': page,
        'base_template': base_template,
        'available_languages': ['en', 'es'],
        }
    return render_to_response('claiming.html', cdict)
Beispiel #6
0
 def get_context(self, request, *args, **kwargs):
     if self.language != 'en':
         activate(self.language)
     else:
         deactivate_all()
     return super(PortalSearchPage, self).get_context(
         request, *args, **kwargs)
Beispiel #7
0
    def test_evaluate_multiple(self):
        from django.utils.translation import deactivate_all
        deactivate_all()  # So that we can test this "OR".

        # Descriptor, solution, is_correct, variable_types.
        tests = [
            ("100 | -100", "100", True, [Integer, Integer]),
            ("100 | -100", "-100", True, [Integer, Integer]),
            ("100 | -100", "200", False, [Integer, Integer]),
            ("100 | -100", "kifla", InvalidSolution, [Integer, Integer]),
            ("100 | sarma", "kifla", False, [Integer, String]),
            ("100 | sarma", "100", True, [Integer, String]),
            ("100 | sarma", "sarma", True, [Integer, String]),
            ("{1,2} | {1}", "1,2", True, [MultiSet, MultiSet]),
            ("{1,2} | {1}", "1", True, [MultiSet, MultiSet]),
            ("{1,2} | {1}", "2", False, [MultiSet, MultiSet]),
            ("sarma|sarma", "sarma", True, [String, String]),
            ("sarma|sarma", "sarma|sarma", False, [String, String]),
            ("sarma\\|sarma", "sarma|sarma", True, [String]),
            ("sarma\\|sarma", "sarma", False, [String]),
            ("sarma\\|sarma", "sarma|sarma", True, [String]),
            ("sarma\\\\|kifla", "kifla", True, [String, String]),
            ("sarma\\\\|kifla", "sarma\\", True, [String, String]),
            ("sarma\\\\|kifla", "sarma", False, [String, String]),
        ]

        for descriptor, solution, is_correct, variable_types in tests:
            self.assertVariableTypes(variable_types, [descriptor])

        _tests = [(a, b, c) for a, b, c, d in tests]
        self.assertMultipleEqualOrRaise(check_result, _tests)
Beispiel #8
0
 def get_context(self, request, *args, **kwargs):
     if self.language != 'en':
         activate(self.language)
     else:
         deactivate_all()
     context = super(
         TagResultsPage, self).get_context(request, *args, **kwargs)
     return context
    def test_get_active(self):
        deactivate_all()
        # No active language, returns default
        self.assertEqual(languages.get_active(), 'cs')

        activate('en')
        # Active language is returned
        self.assertEqual(languages.get_active(), 'en')
Beispiel #10
0
 def perform_authentication(self, request):
     super().perform_authentication(request)
     # Change current langugage if authentication is successful
     # and we know the user's preference
     if getattr(request.user, 'language', False):
         activate(request.user.language)
     else:
         deactivate_all()
Beispiel #11
0
 def __exit__(self, exc_type, exc_value, traceback):
     # type: (Any, Any, Any) -> None
     if self.old_language is None:
         translation.deactivate_all()
     elif self.deactivate:
         translation.deactivate()
     else:
         translation.activate(self.old_language)
Beispiel #12
0
 def test_get_sample_solution_multiple(self):
     from django.utils.translation import deactivate_all
     deactivate_all()  # So that we can test this "OR".
     tests = [
         ("00:50 | sarma | [biftek, kifla]", "00:50 OR sarma OR biftek,kifla"),
         ("100 | 100.00 | -100", "100 OR 100.00 OR -100"),
     ]
     self.assertGetSampleSolution(tests)
Beispiel #13
0
    def test_build_localized_field_name(self):
        self.assertEqual(utils.build_localized_field_name('title', 'fr'), 'title_fr')
        self.assertEqual(utils.build_localized_field_name('title', 'fr-ca'), 'title_fr_ca')

        translation.deactivate_all()
        self.assertEqual(utils.build_localized_field_name('title'), 'title_en')

        translation.activate('it')
        self.assertEqual(utils.build_localized_field_name('title'), 'title_it')
Beispiel #14
0
    def render(self, context):
        current_language = translation.get_language()

        translation.deactivate_all()

        rendered = self.nodelist.render(context)

        translation.activate(current_language)

        return rendered
Beispiel #15
0
    def test_get_recovery_url_no_active_translation(self):
        """
        When no translation is active, the locale is /en-US/.

        This happens in management commands, such as the Django shell.
        """
        user = self.user_model.objects.get(username='******')
        deactivate_all()
        url = user.get_recovery_url()
        assert url.startswith('/en-US/users/account/recover/')
Beispiel #16
0
 def wrapped(*args, **kwargs):
     from django.utils import translation
     saved_locale = translation.get_language()
     translation.deactivate_all()
     try:
         res = handle_func(*args, **kwargs)
     finally:
         if saved_locale is not None:
             translation.activate(saved_locale)
     return res
Beispiel #17
0
    def execute(self, *args, **options):
        """
        Try to execute this command, performing system checks if needed (as
        controlled by attributes ``self.requires_system_checks`` and
        ``self.requires_model_validation``, except if force-skipped).
        """
        if options.get('no_color'):
            self.style = no_style()
            self.stderr.style_func = None
        if options.get('stdout'):
            self.stdout = OutputWrapper(options['stdout'])
        if options.get('stderr'):
            self.stderr = OutputWrapper(options.get('stderr'), self.stderr.style_func)

        if self.can_import_settings:
            from django.conf import settings  # NOQA

        saved_locale = None
        if not self.leave_locale_alone:
            # Only mess with locales if we can assume we have a working
            # settings file, because django.utils.translation requires settings
            # (The final saying about whether the i18n machinery is active will be
            # found in the value of the USE_I18N setting)
            if not self.can_import_settings:
                raise CommandError("Incompatible values of 'leave_locale_alone' "
                                   "(%s) and 'can_import_settings' (%s) command "
                                   "options." % (self.leave_locale_alone,
                                                 self.can_import_settings))
            # Deactivate translations, because django-admin creates database
            # content like permissions, and those shouldn't contain any
            # translations.
            from django.utils import translation
            saved_locale = translation.get_language()
            translation.deactivate_all()

        try:
            if (self.requires_system_checks and
                    not options.get('skip_validation') and  # Remove at the end of deprecation for `skip_validation`.
                    not options.get('skip_checks')):
                self.check()
            output = self.handle(*args, **options)
            if output:
                if self.output_transaction:
                    # This needs to be imported here, because it relies on
                    # settings.
                    from django.db import connections, DEFAULT_DB_ALIAS
                    connection = connections[options.get('database', DEFAULT_DB_ALIAS)]
                    if connection.ops.start_transaction_sql():
                        self.stdout.write(self.style.SQL_KEYWORD(connection.ops.start_transaction_sql()))
                self.stdout.write(output)
                if self.output_transaction:
                    self.stdout.write('\n' + self.style.SQL_KEYWORD(connection.ops.end_transaction_sql()))
        finally:
            if saved_locale is not None:
                translation.activate(saved_locale)
Beispiel #18
0
    def wrapped(*args, **kwargs):
        from django.utils import translation

        saved_locale = translation.get_language()
        translation.deactivate_all()
        try:
            res = handle_func(*args, **kwargs)
        finally:
            if saved_locale is not None:
                translation.activate(saved_locale)
        return res
Beispiel #19
0
 def verbose_name_raw(self):
     """
     There are a few places where the untranslated verbose name is needed
     (so that we get the same value regardless of currently active
     locale).
     """
     lang = get_language()
     deactivate_all()
     raw = force_text(self.verbose_name)
     activate(lang)
     return raw
 def wrapped(*args, **kwargs):
     from django.utils import translation
     saved_locale = translation.get_language()
     translation.deactivate_all()
     try:
         res = handle_func(*args, **kwargs)
         #print('【django.core.management.base.no_transactions】res:', res)
     finally:
         if saved_locale is not None:
             translation.activate(saved_locale)
     return res
    def test_field_value_pairs(self):
        """The |field_value_pairs filter does what it should"""
        deactivate_all()
        absence = factories.AbsenceFactory.create(
            starts_on=dt.date(2020, 1, 1))
        pairs = dict(field_value_pairs(absence))

        self.assertEqual(pairs["Starts on"], "01.01.2020")
        self.assertEqual(pairs["Ends on"], None)
        self.assertEqual(pairs["Reason"], "vacation")
        self.assertEqual(pairs["Is vacation"], "yes")
Beispiel #22
0
    def render(self, context):
        """Render."""
        current_language = translation.get_language()

        translation.deactivate_all()

        rendered = self.nodelist.render(context)

        translation.activate(current_language)

        return rendered
Beispiel #23
0
 def verbose_name_raw(self):
     """
     There are a few places where the untranslated verbose name is needed
     (so that we get the same value regardless of currently active
     locale).
     """
     lang = get_language()
     deactivate_all()
     raw = force_text(self.verbose_name)
     activate(lang)
     return raw
Beispiel #24
0
    def execute(self, *args, **options):
        """
        尝试执行这个命令  如果需要执行系统检查
        Try to execute this command, performing system checks if needed
        (as controlled by the ``requires_system_checks`` attribute, except if force-skipped).
        除非强制跳过
        """
        # 1、判断颜色相关信息
        if options['no_color']:
            self.style = no_style()
            self.stderr.style_func = None
        if options.get('stdout'):
            self.stdout = OutputWrapper(options['stdout'])
        if options.get('stderr'):
            self.stderr = OutputWrapper(options['stderr'],
                                        self.stderr.style_func)

        # 2、TODO 这个干嘛的? 2021年7月2日14:16:43
        saved_locale = None
        if not self.leave_locale_alone:
            # Deactivate translations, because django-admin creates database
            # 停用 translations 因为django-admin创建数据库内容 ,像权限这些不应该包含translations
            # content like permissions, and those shouldn't contain any
            # translations.
            from django.utils import translation
            saved_locale = translation.get_language()
            translation.deactivate_all()

        try:
            # 3、检查相关的选项
            if self.requires_system_checks and not options.get('skip_checks'):
                self.check()
            if self.requires_migrations_checks:
                self.check_migrations()
            #4、 真正的执行 - nnd 接口,面向对象啊
            output = self.handle(*args, **options)

            if output:
                if self.output_transaction:
                    connection = connections[options.get(
                        'database', DEFAULT_DB_ALIAS)]
                    output = '%s\n%s\n%s' % (
                        self.style.SQL_KEYWORD(
                            connection.ops.start_transaction_sql()),
                        output,
                        self.style.SQL_KEYWORD(
                            connection.ops.end_transaction_sql()),
                    )
                self.stdout.write(output)
        finally:
            if saved_locale is not None:
                translation.activate(saved_locale)
        return output
Beispiel #25
0
    def test_get_recovery_url_no_active_translation(self):
        """
        When no translation is active, the locale is /en-US/.

        This happens in management commands, such as the Django shell.

        See: https://bugzilla.mozilla.org/show_bug.cgi?id=1477016
        """
        user = self.user_model.objects.get(username="******")
        deactivate_all()
        url = user.get_recovery_url()
        assert url.startswith("/en-US/users/account/recover/")
Beispiel #26
0
    def test_language_override_no_course_force_lang_no_langcode(self):
        if self.course.force_lang:
            self.course.force_lang = ""
            self.course.save()

        translation.deactivate_all()
        with LanguageOverride(course=self.course):
            self.assertEqual(translation.get_language(), "de")
            self.assertEqual(translation.ugettext("user"), u"Benutzer")

        self.assertEqual(translation.get_language(), None)
        self.assertEqual(translation.ugettext("whatever"), "whatever")
    def setUp(self):
        self.user = User.objects.create_superuser("admin", "*****@*****.**",
                                                  "blabla")
        deactivate_all()

        if settings.USE_CUSTOM_SITE:
            self.test_site = CustomSite.objects.create(host="testserver",
                                                       is_default=True,
                                                       title="Test Site")
        else:
            self.test_site = Site.objects.create(host="testserver",
                                                 is_default=True)
Beispiel #28
0
    def test_language_override_no_course_force_lang_no_langcode(self):
        if self.course.force_lang:
            self.course.force_lang = ""
            self.course.save()

        translation.deactivate_all()
        with LanguageOverride(course=self.course):
            self.assertEqual(translation.get_language(), "de")
            self.assertEqual(translation.ugettext("user"), u"Benutzer")

        self.assertEqual(translation.get_language(), None)
        self.assertEqual(translation.ugettext("whatever"), "whatever")
Beispiel #29
0
    def execute(self, *args, **options):
        """
        Try to execute this command, performing system checks if needed (as
        controlled by the ``requires_system_checks`` attribute, except if
        force-skipped).
        """
        if options.get('no_color'):
            self.style = no_style()
            self.stderr.style_func = None
        if options.get('stdout'):
            self.stdout = OutputWrapper(options['stdout'])
        if options.get('stderr'):
            self.stderr = OutputWrapper(options.get('stderr'), self.stderr.style_func)

        saved_locale = None
        if not self.leave_locale_alone:
            # Only mess with locales if we can assume we have a working
            # settings file, because django.utils.translation requires settings
            # (The final saying about whether the i18n machinery is active will be
            # found in the value of the USE_I18N setting)
            if not self.can_import_settings:
                raise CommandError("Incompatible values of 'leave_locale_alone' "
                                   "(%s) and 'can_import_settings' (%s) command "
                                   "options." % (self.leave_locale_alone,
                                                 self.can_import_settings))
            # Deactivate translations, because django-admin creates database
            # content like permissions, and those shouldn't contain any
            # translations.
            from django.utils import translation
            saved_locale = translation.get_language()
            translation.deactivate_all()

        try:
            if (self.requires_system_checks and
                    not options.get('skip_validation') and  # Remove at the end of deprecation for `skip_validation`.
                    not options.get('skip_checks')):
                self.check()
            output = self.handle(*args, **options)
            if output:
                if self.output_transaction:
                    # This needs to be imported here, because it relies on
                    # settings.
                    from django.db import connections, DEFAULT_DB_ALIAS
                    connection = connections[options.get('database', DEFAULT_DB_ALIAS)]
                    if connection.ops.start_transaction_sql():
                        self.stdout.write(self.style.SQL_KEYWORD(connection.ops.start_transaction_sql()))
                self.stdout.write(output)
                if self.output_transaction:
                    self.stdout.write('\n' + self.style.SQL_KEYWORD(connection.ops.end_transaction_sql()))
        finally:
            if saved_locale is not None:
                translation.activate(saved_locale)
Beispiel #30
0
 def _set_course_lang(self, action):
     # type: (Text) -> None
     if self.course.force_lang and self.course.force_lang.strip():
         if action == "activate":
             self.old_language = translation.get_language()
             translation.activate(self.course.force_lang)
         else:
             if self.old_language is None:
                 # This should be a rare case, but get_language() can be None.
                 # See django.utils.translation.override.__exit__()
                 translation.deactivate_all()
             else:
                 translation.activate(self.old_language)
Beispiel #31
0
 def _set_course_lang(self, action):
     # type: (Text) -> None
     if self.course.force_lang and self.course.force_lang.strip():
         if action == "activate":
             self.old_language = translation.get_language()
             translation.activate(self.course.force_lang)
         else:
             if self.old_language is None:
                 # This should be a rare case, but get_language() can be None.
                 # See django.utils.translation.override.__exit__()
                 translation.deactivate_all()
             else:
                 translation.activate(self.old_language)
Beispiel #32
0
    def execute(self, *args, **options):
        """
        Try to execute this command, performing system checks if needed (as
        controlled by the ``requires_system_checks`` attribute, except if
        force-skipped).
        """
        if options['no_color']:
            self.style = no_style()
            self.stderr.style_func = None
        if options.get('stdout'):
            self.stdout = OutputWrapper(options['stdout'])
        if options.get('stderr'):
            self.stderr = OutputWrapper(options['stderr'], self.stderr.style_func)

        saved_locale = None
        if not self.leave_locale_alone:
            # Only mess with locales if we can assume we have a working
            # settings file, because django.utils.translation requires settings
            # (The final saying about whether the i18n machinery is active will be
            # found in the value of the USE_I18N setting)
            if not self.can_import_settings:
                raise CommandError("Incompatible values of 'leave_locale_alone' "
                                   "(%s) and 'can_import_settings' (%s) command "
                                   "options." % (self.leave_locale_alone,
                                                 self.can_import_settings))
            # Deactivate translations, because django-admin creates database
            # content like permissions, and those shouldn't contain any
            # translations.
            from django.utils import translation
            saved_locale = translation.get_language()
            translation.deactivate_all()

        try:
            if self.requires_system_checks and not options.get('skip_checks'):
                self.check()
            if self.requires_migrations_checks:
                self.check_migrations()
            output = self.handle(*args, **options)
            if output:
                if self.output_transaction:
                    connection = connections[options.get('database', DEFAULT_DB_ALIAS)]
                    output = '%s\n%s\n%s' % (
                        self.style.SQL_KEYWORD(connection.ops.start_transaction_sql()),
                        output,
                        self.style.SQL_KEYWORD(connection.ops.end_transaction_sql()),
                    )
                self.stdout.write(output)
        finally:
            if saved_locale is not None:
                translation.activate(saved_locale)
        return output
Beispiel #33
0
    def test_get_language(self):
        # Full? Returns first level
        translation.activate('en-us')
        self.assertEqual(utils.get_language(), 'en')

        # Unsupported? Returns fallback one
        translation.activate('ru')
        self.assertEqual(utils.get_fallback_language(), 'en')
        self.assertEqual(utils.get_language(), utils.get_fallback_language())

        # Deactivating all should returns fallback one
        translation.deactivate_all()
        self.assertEqual(utils.get_fallback_language(), 'en')
        self.assertEqual(utils.get_language(), utils.get_fallback_language())
Beispiel #34
0
    def test_can_redirect_article_from_legacy_urls(self):
        from django.utils.translation import deactivate_all

        article = ArticleFactory()
        url = '/revue/{journal_code}/{issue_year}/v/n{issue_number}/{article_localidentifier}.html'.format(  # noqa
            journal_code=article.issue.journal.code,
            issue_year=article.issue.year,
            issue_number=article.issue.number,
            article_localidentifier=article.localidentifier)

        resp = self.client.get(url)

        assert resp.url == reverse(
            'public:journal:article_detail',
            kwargs=dict(journal_code=article.issue.journal.code,
                        issue_slug=article.issue.volume_slug,
                        issue_localid=article.issue.localidentifier,
                        localid=article.localidentifier))
        assert "/fr/" in resp.url
        assert resp.status_code == 301

        deactivate_all()
        resp = self.client.get(url + "?lang=en")

        assert resp.url == reverse(
            'public:journal:article_detail',
            kwargs=dict(journal_code=article.issue.journal.code,
                        issue_slug=article.issue.volume_slug,
                        issue_localid=article.issue.localidentifier,
                        localid=article.localidentifier))
        assert "/en/" in resp.url
        assert resp.status_code == 301

        url = '/en/revue/{journal_code}/{issue_year}/v/n{issue_number}/{article_localidentifier}.html'.format(  # noqa
            journal_code=article.issue.journal.code,
            issue_year=article.issue.year,
            issue_number=article.issue.number,
            article_localidentifier=article.localidentifier)
        deactivate_all()
        resp = self.client.get(url)

        assert resp.url == reverse(
            'public:journal:article_detail',
            kwargs=dict(journal_code=article.issue.journal.code,
                        issue_slug=article.issue.volume_slug,
                        issue_localid=article.issue.localidentifier,
                        localid=article.localidentifier))

        assert "/en/" in resp.url
        assert resp.status_code == 301
Beispiel #35
0
def about(request, language='en'):
    """Return our 'about' calculation-explainer page in Engish or Spanish"""
    if language == 'es':
        activate('es')
        es = True
    else:
        deactivate_all()
        es = False
    cdict = {
        'base_template': base_template,
        'available_languages': ['en', 'es'],
        'es': es
        }
    return render_to_response('about.html', cdict)
Beispiel #36
0
def chlocale(url, locale):
    """
    Changes the URL's locale prefix if the path is not locale-independent.
    Otherwise removes locale prefix.
    XXX: Taken from localeurl (https://bitbucket.org/carljm/django-localeurl/)
    """
    def strip_script_prefix(url):
        """
        Strips the SCRIPT_PREFIX from the URL. Because this function is meant for
        use in templates, it assumes the URL starts with the prefix.
        """
        assert url.startswith(urlresolvers.get_script_prefix()), \
            "URL must start with SCRIPT_PREFIX: %s" % url
        pos = len(urlresolvers.get_script_prefix()) - 1
        return url[:pos], url[pos:]

    def strip_path(path):
        """
        Separates the locale prefix from the rest of the path. If the path does not
        begin with a locale it is returned without change.
        """
        SUPPORTED_LOCALES = dict(
            (code.lower(), name) for code, name in settings.LANGUAGES)
        # Issue #15. Sort locale codes to avoid matching e.g. 'pt' before 'pt-br'
        LOCALES_RE = '|'.join(
            sorted(SUPPORTED_LOCALES.keys(),
                   key=lambda i: len(i),
                   reverse=True))
        PATH_RE = re.compile(r'^/(?P<locale>%s)(?P<path>.*)$' % LOCALES_RE,
                             re.I)

        check = PATH_RE.match(path)
        if check:
            path_info = check.group('path') or '/'
            if path_info.startswith('/'):
                return check.group('locale'), path_info
        return '', path

    _, path = strip_script_prefix(url)
    _, path = strip_path(path)

    old_locale = translation.get_language()
    translation.deactivate_all()
    translation.activate(locale)
    try:
        url = locale + path
    finally:
        translation.activate(old_locale)

    return '/' + url
Beispiel #37
0
    def setUp(self):
        domain = Domain.objects.create(name="test")
        division = Division.objects.create(name="localities",
                                           domain=domain,
                                           index="3")
        self.home = Entity.objects.create(name="earth",
                                          division=division,
                                          id=1111,
                                          code="1111")
        self.away = Entity.objects.create(name="the moon",
                                          division=division,
                                          id=9999,
                                          code="41")
        self.candidate_list = CandidateList.objects.create(name="list",
                                                           ballot="l",
                                                           entity=self.home)

        self.common_user = User.objects.create_user("commoner",
                                                    "*****@*****.**",
                                                    "pass")
        self.common_user.profile.locality = self.home
        self.common_user.profile.save()
        self.common2_user = User.objects.create_user("commoner2",
                                                     "*****@*****.**",
                                                     "pass")
        self.common2_user.profile.locality = self.home
        self.common2_user.profile.save()
        self.candidate_user = User.objects.create_user(
            "candidate", "*****@*****.**", "pass")
        self.candidate_user.profile.locality = self.home
        self.candidate_user.profile.save()
        Candidate.objects.create(user=self.candidate_user,
                                 candidate_list=self.candidate_list)
        self.editor = User.objects.create_user("editor", "*****@*****.**",
                                               "pass")
        self.editor.profile.locality = self.home
        self.editor.profile.is_editor = True
        self.editor.profile.save()
        self.q = Question.objects.create(author=self.common_user,
                                         subject="why?",
                                         entity=self.home)
        self.a = self.q.answers.create(author=self.candidate_user,
                                       content="because the world is round")
        self.site1 = Site.objects.create(domain='abc.com')
        self.site2 = Site.objects.create(domain='fun.com')
        self.q.tags.create(name="abc")
        self.q.tags.create(name="def")
        translation.deactivate_all()
        self.patch = patch('requests.session')
        self.mock_request = self.patch.start()().request
Beispiel #38
0
def about(request, language='en'):
    """Return our 'about' calculation-explainer page in Engish or Spanish"""
    if language == 'es':
        activate('es')
        es = True
    else:
        deactivate_all()
        es = False
    cdict = {
        'base_template': base_template,
        'available_languages': ['en', 'es'],
        'es': es
        }
    return render_to_response('about.html', cdict)
Beispiel #39
0
    def test_localized_ref(cls):
        """Tests whether the :see:LocalizedRef expression properly works."""

        obj = cls.TestModel1.objects.create(name="bla bla")
        for i in range(0, 10):
            cls.TestModel2.objects.create(
                text=LocalizedValue(
                    dict(
                        en="text_%d_en" % i,
                        ro="text_%d_ro" % i,
                        nl="text_%d_nl" % i,
                    )),
                other=obj,
            )

        def create_queryset(ref):
            return cls.TestModel1.objects.annotate(mytexts=ref).values_list(
                "mytexts", flat=True)

        # assert that it properly selects the currently active language
        for lang_code, _ in settings.LANGUAGES:
            translation.activate(lang_code)
            queryset = create_queryset(LocalizedRef("features__text"))

            for index, value in enumerate(queryset):
                assert translation.get_language() in value
                assert str(index) in value

        # ensure that the default language is used in case no
        # language is active at all
        translation.deactivate_all()
        queryset = create_queryset(LocalizedRef("features__text"))
        for index, value in enumerate(queryset):
            assert settings.LANGUAGE_CODE in value
            assert str(index) in value

        # ensures that overriding the language works properly
        queryset = create_queryset(LocalizedRef("features__text", "ro"))
        for index, value in enumerate(queryset):
            assert "ro" in value
            assert str(index) in value

        # ensures that using this in combination with ArrayAgg works properly
        queryset = create_queryset(
            ArrayAgg(LocalizedRef("features__text", "ro"))).first()
        assert isinstance(queryset, list)
        for value in queryset:
            assert "ro" in value
Beispiel #40
0
 def test_date_ranges(self):
     """The date ranges utility returns expected values"""
     deactivate_all()
     self.assertEqual(
         date_ranges(),
         [
             ("2020-02-24", "2020-03-01", "this week"),
             ("2020-02-17", "2020-02-23", "last week"),
             ("2020-02-01", "2020-02-29", "this month"),
             ("2020-01-01", "2020-01-31", "last month"),
             ("2020-01-01", "2020-03-31", "this quarter"),
             ("2019-10-01", "2019-12-31", "last quarter"),
             ("2020-01-01", "2020-12-31", "this year"),
             ("2019-01-01", "2019-12-31", "last year"),
         ],
     )
def chlocale(url, locale):
    """
    Changes the URL's locale prefix if the path is not locale-independent.
    Otherwise removes locale prefix.
    XXX: Taken from localeurl (https://bitbucket.org/carljm/django-localeurl/)
    """
    def strip_script_prefix(url):
        """
        Strips the SCRIPT_PREFIX from the URL. Because this function is meant for
        use in templates, it assumes the URL starts with the prefix.
        """
        assert url.startswith(urlresolvers.get_script_prefix()), \
            "URL must start with SCRIPT_PREFIX: %s" % url
        pos = len(urlresolvers.get_script_prefix()) - 1
        return url[:pos], url[pos:]
        
    def strip_path(path):
        """
        Separates the locale prefix from the rest of the path. If the path does not
        begin with a locale it is returned without change.
        """
        SUPPORTED_LOCALES = dict(
            (code.lower(), name) for code, name in settings.LANGUAGES)
        # Issue #15. Sort locale codes to avoid matching e.g. 'pt' before 'pt-br'
        LOCALES_RE = '|'.join(
            sorted(SUPPORTED_LOCALES.keys(), key=lambda i: len(i), reverse=True))
        PATH_RE = re.compile(r'^/(?P<locale>%s)(?P<path>.*)$' % LOCALES_RE, re.I)
        
        check = PATH_RE.match(path)
        if check:
            path_info = check.group('path') or '/'
            if path_info.startswith('/'):
                return check.group('locale'), path_info
        return '', path

    _, path = strip_script_prefix(url)
    _, path = strip_path(path)
    
    old_locale = translation.get_language()
    translation.deactivate_all()
    translation.activate(locale)
    try:
        url =  locale + path
    finally:
        translation.activate(old_locale)

    return '/' + url
def test_i18n(build_tree, template_render_tag, template_context):

    from sitetree.toolbox import register_i18n_trees

    build_tree(
        {'alias': 'i18tree'},
        [{'title': 'My title', 'url': '/url_default/'}],
    )
    build_tree(
        {'alias': 'i18tree_ru'},
        [{'title': 'Заголовок', 'url': '/url_ru/'}],
    )
    build_tree(
        {'alias': 'i18tree_pt-br'},
        [{'title': 'Meu Título', 'url': '/url_pt-br/'}],
    )
    build_tree(
        {'alias': 'i18tree_zh-hans'},
        [{'title': '我蒂特', 'url': '/url_zh-hans/'}],
    )
    register_i18n_trees(['i18tree'])

    activate('en')
    result = template_render_tag('sitetree', 'sitetree_tree from "i18tree"', template_context())

    assert '/url_default/' in result
    assert 'My title' in result

    activate('ru')
    result = template_render_tag('sitetree', 'sitetree_tree from "i18tree"', template_context())

    assert '/url_ru/' in result
    assert 'Заголовок' in result

    activate('pt-br')
    result = template_render_tag('sitetree', 'sitetree_tree from "i18tree"', template_context())

    assert '/url_pt-br/' in result
    assert 'Meu Título' in result

    activate('zh-hans')
    result = template_render_tag('sitetree', 'sitetree_tree from "i18tree"', template_context())

    assert '/url_zh-hans/' in result
    assert '我蒂特' in result

    deactivate_all()
Beispiel #43
0
def about(request, language="en"):
    """Return our 'about' calculation-explainer page in Engish or Spanish"""
    if language == "es":
        activate("es")
        es = True
    else:
        deactivate_all()
        es = False
    cdict = {
        "base_template": base_template,
        "available_languages": ["en", "es"],
        "es": es,
        "language": language,
        "show_banner": True,
        "show_mega_menu": True,
    }
    return render(request, "retirement_api/about.html", cdict)
Beispiel #44
0
    def execute(self, *args, **options):
        """
        Try to execute this command, performing system checks if needed (as
        controlled by the ``requires_system_checks`` attribute, except if
        force-skipped).
        """
        if options['no_color']:
            self.style = no_style()
            self.stderr.style_func = None
        if options.get('stdout'):
            self.stdout = OutputWrapper(options['stdout'])
        if options.get('stderr'):
            self.stderr = OutputWrapper(options['stderr'],
                                        self.stderr.style_func)

        saved_locale = None
        if not self.leave_locale_alone:
            # Deactivate translations, because django-admin creates database
            # content like permissions, and those shouldn't contain any
            # translations.
            from django.utils import translation
            saved_locale = translation.get_language()
            translation.deactivate_all()

        try:
            if self.requires_system_checks and not options.get('skip_checks'):
                self.check()
            if self.requires_migrations_checks:
                self.check_migrations()
            output = self.handle(*args, **options)
            if output:
                if self.output_transaction:
                    connection = connections[options.get(
                        'database', DEFAULT_DB_ALIAS)]
                    output = '%s\n%s\n%s' % (
                        self.style.SQL_KEYWORD(
                            connection.ops.start_transaction_sql()),
                        output,
                        self.style.SQL_KEYWORD(
                            connection.ops.end_transaction_sql()),
                    )
                self.stdout.write(output)
        finally:
            if saved_locale is not None:
                translation.activate(saved_locale)
        return output
Beispiel #45
0
    def get_patterns(self):
        self.discover_plugins()

        # We want untranslated name of the plugin for its slug so we deactivate translation
        lang = get_language()
        deactivate_all()

        try:
            url_patterns = []
            for plugin in self.get_all_plugins():
                p = plugin()
                slug = slugify(force_unicode(normalize_name(p.__class__.__name__)))
                url_patterns += patterns("", url(r"^plugin/%s/" % (slug,), include(p.plugin_urls)))
        finally:
            # Reactivate translation
            activate(lang)

        return url_patterns
Beispiel #46
0
    def test_localized_lookup(self):
        """Tests whether localized lookup properly works."""

        self.TestModel.objects.create(text=LocalizedValue(
            dict(en='text_en', ro='text_ro', nl='text_nl')), )

        # assert that it properly lookups the currently active language
        for lang_code, _ in settings.LANGUAGES:
            translation.activate(lang_code)
            assert self.TestModel.objects.filter(text='text_' +
                                                 lang_code).exists()

        # ensure that the default language is used in case no
        # language is active at all
        translation.deactivate_all()
        assert self.TestModel.objects.filter(text='text_en').exists()

        # ensure that hstore lookups still work
        assert self.TestModel.objects.filter(text__ro='text_ro').exists()
Beispiel #47
0
def get_translations_for_page(page):
    translations = []
    deactivate_all()
    activate(page.language)
    try:
        trans_holder = page.get_children().get(title="Translations")
        if page.live:
            translations.append(page.specific)
        translations.extend(trans_holder.get_children().live().specific())
    except Page.DoesNotExist:
        # Check if page exists within the translation folder
        parent = page.get_parent()
        if parent.title == "Translations":
            if parent.get_parent().live:
                translations.append(parent.get_parent().specific)
            live_children = parent.get_children().live()
            if live_children:
                translations.extend(live_children.specific())
    return translations
Beispiel #48
0
    def execute(self, *args, **options):
        """
        Try to execute this command, performing system checks if needed (as
        controlled by the ``requires_system_checks`` attribute, except if
        force-skipped).
        """
        if options['no_color']:
            self.style = no_style()
            self.stderr.style_func = None
        if options.get('stdout'):
            self.stdout = OutputWrapper(options['stdout'])
        if options.get('stderr'):
            self.stderr = OutputWrapper(options['stderr'], self.stderr.style_func)

        saved_locale = None
        if not self.leave_locale_alone:
            # Deactivate translations, because django-admin creates database
            # content like permissions, and those shouldn't contain any
            # translations.
            from django.utils import translation
            saved_locale = translation.get_language()
            translation.deactivate_all()

        try:
            if self.requires_system_checks and not options.get('skip_checks'):
                self.check()
            if self.requires_migrations_checks:
                self.check_migrations()
            output = self.handle(*args, **options)
            if output:
                if self.output_transaction:
                    connection = connections[options.get('database', DEFAULT_DB_ALIAS)]
                    output = '%s\n%s\n%s' % (
                        self.style.SQL_KEYWORD(connection.ops.start_transaction_sql()),
                        output,
                        self.style.SQL_KEYWORD(connection.ops.end_transaction_sql()),
                    )
                self.stdout.write(output)
        finally:
            if saved_locale is not None:
                translation.activate(saved_locale)
        return output
    def test_permalink(self):
        """permalink property should be constructed from base url and absolute url, without any language code"""
        current_lang = get_language()

        # if non-default language is active, should stay activate
        activate("he")
        doc = Document.objects.create(id=1)
        site_domain = Site.objects.get_current().domain.rstrip("/")
        # document url should follow directly after site domain,
        # with no language code
        assert f"{site_domain}/documents/1/" in doc.permalink
        # activated language code should persist
        assert get_language() == "he"

        # handle case whre no language active
        deactivate_all()
        assert f"{site_domain}/documents/1/" in doc.permalink

        # reactivate previous default (in case it matters for other tests)
        activate(current_lang)
Beispiel #50
0
    def get_patterns(self):
        self.discover_plugins()

        # We want untranslated name of the plugin for its slug so we deactivate translation
        lang = get_language()
        deactivate_all()

        try:
            url_patterns = []
            for plugin in self.registered_plugins:
                p = plugin()
                slug = slugify(force_str(normalize_name(p.__class__.__name__)))
                url_patterns += [
                    re_path(r'^plugin/%s/' % (slug,), include(p.plugin_urls)),
                ]
        finally:
            # Reactivate translation
            activate(lang)

        return url_patterns
def test_i18n(source_listdics, settings):

    table = Table(source=source_listdics, plugins=[I18nPlugin()])

    assert len(table.get_assets_css()) == 1
    assert len(table.get_assets_js()) == 1

    config = table.get_config()
    assert 'language' not in config  # Unable to autodetect lang

    activate('ru')

    # Autodetect.
    config = table.get_config()
    assert 'Russian' in config['language']['url']

    # Manual.
    config = Table(source=source_listdics, plugins=[I18nPlugin('de')]).get_config()
    assert 'German' in config['language']['url']

    deactivate_all()
def move_all_color_into_groups(apps, schema_editor):
    LocationGroupCategory = apps.get_model('mapdata', 'LocationGroupCategory')
    category = LocationGroupCategory.objects.get(name='groups')

    colors = {}
    for model_name in ('Level', 'Space', 'Area', 'POI'):
        model = apps.get_model('mapdata', model_name)
        for obj in model.objects.filter(color__isnull=False):
            colors.setdefault(obj.color, []).append(obj)

    from c3nav.mapdata.models import Location
    for color, objects in colors.items():
        titles = {lang: [] for lang in set(chain(*(obj.titles.keys() for obj in objects)))}
        for obj in objects:
            for lang in titles.keys():
                translation.activate(lang)
                titles[lang].append(Location(titles=obj.titles).title)
                translation.deactivate_all()
        titles = {lang: ', '.join(values) for lang, values in titles.items()}
        group = category.groups.create(can_search=False, can_describe=False, color=color, titles=titles)
        for obj in objects:
            obj.groups.add(group)
Beispiel #53
0
 def setUp(self):
     domain = Domain.objects.create(name="test")
     division = Division.objects.create(name="localities", domain=domain)
     self.entity = Entity.objects.create(name="the moon",
                                         division=division,
                                         id=settings.QNA_DEFAULT_ENTITY_ID)
     self.common_user = User.objects.create_user("commoner",
                                                 "*****@*****.**",
                                                 "pass")
     self.common_user.profile.locality = self.entity
     self.common_user.profile.save()
     self.common2_user = User.objects.create_user("commoner2",
                                                  "*****@*****.**",
                                                  "pass")
     self.common2_user.profile.locality = self.entity
     self.common2_user.profile.save()
     self.candidate_user = User.objects.create_user(
         "candidate", "*****@*****.**", "pass")
     self.candidate_user.profile.locality = self.entity
     self.candidate_user.profile.is_candidate = True
     self.candidate_user.profile.save()
     self.editor_user = User.objects.create_user("editor",
                                                 "*****@*****.**",
                                                 "pass")
     self.editor_user.profile.locality = self.entity
     self.editor_user.profile.is_editor = True
     self.editor_user.profile.save()
     self.q = Question.objects.create(author=self.common_user,
                                      subject="why?",
                                      entity=self.entity)
     self.a = self.q.answers.create(author=self.candidate_user,
                                    content="because the world is round")
     self.site1 = Site.objects.create(domain='abc.com')
     self.site2 = Site.objects.create(domain='fun.com')
     self.q.tags.create(name="abc")
     self.q.tags.create(name="def")
     translation.deactivate_all()
     self.patch = patch('requests.session')
     self.mock_request = self.patch.start()().request
Beispiel #54
0
    def setUp(self):
        domain = Domain.objects.create(name="test")
        division = Division.objects.create(name="localities", domain=domain, index="3")
        self.home = Entity.objects.create(name="earth", division=division,
                                            id=1111, code="1111")
        self.away = Entity.objects.create(name="the moon", division=division,
                                            id=9999, code="41")
        self.candidate_list = CandidateList.objects.create(name="list", ballot="l", 
                                                            entity=self.home)

        self.common_user = User.objects.create_user("commoner",
                                "*****@*****.**", "pass")
        self.common_user.profile.locality = self.home
        self.common_user.profile.save()
        self.common2_user = User.objects.create_user("commoner2", 
                                "*****@*****.**", "pass")
        self.common2_user.profile.locality = self.home
        self.common2_user.profile.save()
        self.candidate_user = User.objects.create_user("candidate", 
                                "*****@*****.**", "pass")
        self.candidate_user.profile.locality = self.home
        self.candidate_user.profile.save()
        Candidate.objects.create(user=self.candidate_user, candidate_list=self.candidate_list)
        self.editor = User.objects.create_user("editor", 
                                "*****@*****.**", "pass")
        self.editor.profile.locality = self.home
        self.editor.profile.is_editor = True
        self.editor.profile.save()
        self.q = Question.objects.create(author = self.common_user,
                        subject="why?", entity=self.home)
        self.a = self.q.answers.create(author = self.candidate_user,
                        content="because the world is round")
        self.site1 = Site.objects.create(domain='abc.com')
        self.site2 = Site.objects.create(domain='fun.com')
        self.q.tags.create(name="abc")
        self.q.tags.create(name="def")
        translation.deactivate_all()
        self.patch = patch('requests.session')
        self.mock_request = self.patch.start()().request
Beispiel #55
0
def claiming(request, es=False):
    if es is True:
        activate("es")
        language = "es"
    else:
        language = "en"
        deactivate_all()
    ages = {}
    for age in AgeChoice.objects.all():
        ages[age.age] = _(age.aside)
    page = Page.objects.get(title="Planning your Social Security claiming age")
    tips = {}
    for tooltip in Tooltip.objects.all():
        tips[tooltip.title] = tooltip.text
    questions = {}
    for q in Question.objects.all():
        questions[q.slug] = q
    steps = {}
    for step in Step.objects.all():
        steps[step.title] = step.trans_instructions(language=language)

    cdict = {
        "tstamp": datetime.datetime.now(),
        "steps": steps,
        "questions": questions,
        "tips": tips,
        "ages": ages,
        "page": page,
        "base_template": base_template,
        "available_languages": ["en", "es"],
        "es": es,
        "language": language,
        "show_banner": True,
        "show_mega_menu": True,
        "about_view_name": "retirement_api:" + ("about_es" if es else "about"),
    }

    return render(request, "retirement_api/claiming.html", cdict)
Beispiel #56
0
def get_translations_for_page(page):
    translations = []
    deactivate_all()
    if settings.ENABLE_SITE_LOCALIZATION:
        activate(settings.LANGUAGE_CODE)
    else:
        activate(page.language)

    try:
        trans_holder = page.get_children().get(title="Translations")
        if page.live:
            translations.append(page.specific)
        translations.extend(trans_holder.get_children().live().specific())
    except Page.DoesNotExist:
        # Check if page exists within the translation folder
        parent = page.get_parent()
        if parent.title == "Translations":
            if parent.get_parent().live:
                translations.append(parent.get_parent().specific)
            live_children = parent.get_children().live()
            if live_children:
                translations.extend(live_children.specific())
    return translations
Beispiel #57
0
def translation(language_code, deactivate=False):
    """
    Port of django.utils.translation.override from Django 1.4

    @param language_code: a language code or ``None``. If ``None``, translation
                          is disabled and raw translation strings are used
    @param    deactivate: If ``True``, when leaving the manager revert to the
                          default behaviour (i.e. ``settings.LANGUAGE_CODE``)
                          rather than the translation that was active prior to
                          entering.
    """
    from django.utils import translation
    original = translation.get_language()
    if language_code is not None:
        translation.activate(language_code)
    else:
        translation.deactivate_all()
    try:
        yield
    finally:
        if deactivate:
            translation.deactivate()
        else:
            translation.activate(original)
Beispiel #58
0
 def __enter__(self):
     if self.language is not None:
         translation.activate(self.language)
     else:
         translation.deactivate_all()
Beispiel #59
0
 def tearDown(self):
     translation.deactivate_all()