Ejemplo n.º 1
0
class SwitchLanguageTest(BaseTestCase):
    """change the language from coop-bar popup"""
    def setUp(self):
        self.user = None
        activate(settings.LANGUAGES[0][0])

    def tearDown(self):
        activate(settings.LANGUAGES[0][0])

    @skipIf(not is_localized() or not is_multilang(), "not localized")
    def test_get_language_switcher(self):
        """get article with locale slug"""

        original_text = '*!-+' * 10
        translated_text = ':%@/' * 9

        art1 = get_article_class().objects.create(title="Home",
                                                  content=original_text)

        origin_lang = settings.LANGUAGES[0][0]
        trans_lang = settings.LANGUAGES[1][0]

        setattr(art1, 'title_' + trans_lang, 'Accueil')
        setattr(art1, 'content_' + trans_lang, translated_text)
        art1.save()

        url = reverse('coop_cms_switch_language_popup')

        response = self.client.get(url)
        soup = BeautifulSoup(response.content)
        self.assertEqual(len(soup.select('select#id_language option')),
                         len(settings.LANGUAGES))

    @skipIf(not is_localized() or not is_multilang(), "not localized")
    def test_change_lang(self):
        """change language"""

        original_text = '*!-+' * 10
        translated_text = ':%@/' * 9

        art1 = get_article_class().objects.create(title="Home",
                                                  content=original_text)

        origin_lang = settings.LANGUAGES[0][0]
        trans_lang = settings.LANGUAGES[1][0]

        activate(origin_lang)

        setattr(art1, 'title_' + trans_lang, 'Accueil')
        setattr(art1, 'content_' + trans_lang, translated_text)

        art1.save()

        data = {'language': trans_lang}
        response = self.client.post(reverse('coop_cms_switch_language_popup'),
                                    data=data,
                                    follow=True)
        self.assertEqual(200, response.status_code)
        self.assertEqual(trans_lang, get_language())
Ejemplo n.º 2
0
    def __init__(self, *args, **kwargs):
        super(BaseArticleAdminForm, self).__init__(*args, **kwargs)  # pylint: disable=E1002
        self.article = kwargs.get('instance', None)
        templates = get_article_templates(self.article,
                                          getattr(self, "current_user", None))
        if templates:
            self.fields['template'].widget = forms.Select(choices=templates)

        self.slug_fields = []
        if is_localized():
            for lang_and_name in settings.LANGUAGES:
                from modeltranslation.utils import build_localized_fieldname
                field_name = build_localized_fieldname('slug',
                                                       lang_and_name[0])
                self.slug_fields.append(field_name)
        else:
            self.slug_fields = ['slug']

        can_change_article_slug = can_rewrite_url()

        if not can_change_article_slug:
            can_change_article_slug = (
                self.article.publication != BaseArticle.PUBLISHED
            ) if self.article else True

        for slug_field in self.slug_fields:
            if not can_change_article_slug:
                self.fields[slug_field].widget = ReadOnlyInput()
Ejemplo n.º 3
0
    def test_slug_edition_published_can_edit(self):
        settings.COOP_CMS_CAN_EDIT_ARTICLE_SLUG = True

        self._log_as_staff_editor()

        article_class = get_article_class()

        article = mommy.make(article_class,
                             slug="test",
                             publication=BaseArticle.PUBLISHED)

        view_name = 'admin:%s_%s_change' % (get_model_app(article_class),
                                            get_model_name(article_class))
        url = reverse(view_name, args=[article.id])

        response = self.client.get(url)

        self.assertEqual(200, response.status_code)
        soup = BeautifulSoup(response.content)

        if is_localized():
            from modeltranslation.utils import build_localized_fieldname
            for (lang, _name) in settings.LANGUAGES:
                field_name = build_localized_fieldname('slug', lang)
                self.assertEqual(
                    soup.select("#id_" + field_name)[0]["type"], "text")
        else:
            self.assertEqual(soup.select("#id_slug")[0]["type"], "text")
Ejemplo n.º 4
0
 def handle(self, *args, **options):
     """command"""
     #look for emailing to be sent
     verbose = options.get('verbosity', 1)
     
     if not is_localized():
         print("the site is not localized this is not required")
     
     from modeltranslation.utils import build_localized_fieldname
     
     for alias in Alias.objects.all():
         cursor = connection.cursor()
         
         cursor.execute(
             '''SELECT path, redirect_url FROM coop_cms_alias where id={0}'''.format(alias.id))
         row = cursor.fetchone()
         print(row)
         (path, redirect_url) = row
         
         languages = [x for (x, y) in settings.LANGUAGES]
         
         lang_code = languages[0]
         path_field_name = build_localized_fieldname('path', lang_code)
         redirect_url_field_name = build_localized_fieldname('redirect_url', lang_code)
         if (not getattr(alias, path_field_name)) and (not getattr(alias, redirect_url_field_name)):
             print("update", alias.id, path, redirect_url)
             setattr(alias, path_field_name, path)
             setattr(alias, redirect_url_field_name, redirect_url)
             alias.save()
Ejemplo n.º 5
0
    def handle(self, *args, **options):
        """command"""
        #look for emailing to be sent
        verbose = options.get('verbosity', 1)

        if not is_localized():
            print("the site is not localized this is not required")

        from modeltranslation.utils import build_localized_fieldname

        for alias in Alias.objects.all():
            cursor = connection.cursor()

            cursor.execute(
                '''SELECT path, redirect_url FROM coop_cms_alias where id={0}'''
                .format(alias.id))
            row = cursor.fetchone()
            print(row)
            (path, redirect_url) = row

            languages = [x for (x, y) in settings.LANGUAGES]

            lang_code = languages[0]
            path_field_name = build_localized_fieldname('path', lang_code)
            redirect_url_field_name = build_localized_fieldname(
                'redirect_url', lang_code)
            if (not getattr(alias, path_field_name)) and (not getattr(
                    alias, redirect_url_field_name)):
                print("update", alias.id, path, redirect_url)
                setattr(alias, path_field_name, path)
                setattr(alias, redirect_url_field_name, redirect_url)
                alias.save()
Ejemplo n.º 6
0
def switch_language(request, context):
    if request and request.user.is_staff and is_localized():
        url = reverse('coop_cms_switch_language_popup')
        return make_link(url,
                         _('Switch language'),
                         'globe-americas',
                         classes=['colorbox-form', 'icon'])
Ejemplo n.º 7
0
def change_language(request):
    """change the language"""

    if not is_localized():
        raise Http404

    next_url = request.POST.get('next', None) or request.GET.get('next', None)
    if not next_url:
        url = urlparse(request.META.get('HTTP_REFERER', ''))
        if url:
            next_url = url.path

    if request.method == 'POST':
        lang_code = request.POST.get('language', None)
        after_change_url = request.POST.get('next_url_after_change_lang', None)
        if after_change_url:
            next_url = after_change_url

        go_to_url = _do_change_language(request, lang_code, next_url)
        if go_to_url:
            next_url = go_to_url

    if not next_url:
        next_url = '/'

    return HttpResponseRedirect(next_url)
Ejemplo n.º 8
0
def get_article(slug,
                current_lang=None,
                force_lang=None,
                all_langs=False,
                **kwargs):
    """get article"""

    article_class = get_article_class()
    try:
        return article_class.objects.get(slug=slug, **kwargs)
    except article_class.DoesNotExist:
        # if modeltranslation is installed,
        # if no article correspond to the current language article
        # try to look for slug in default language
        if is_localized():

            from modeltranslation import settings as mt_settings
            from modeltranslation.utils import build_localized_fieldname

            fallback_languages = []
            if current_lang:
                fallback_languages += [
                    current_lang,
                ]
            if force_lang:
                fallback_languages += [
                    force_lang,
                ]

            mt_fallbacks = getattr(settings,
                                   'MODELTRANSLATION_FALLBACK_LANGUAGES', None)
            if mt_fallbacks is None:
                fallback_languages += [
                    mt_settings.DEFAULT_LANGUAGE,
                ]
            else:
                if isinstance(mt_fallbacks, dict):
                    if current_lang in mt_fallbacks:
                        fallback_languages += list(mt_fallbacks[current_lang])
                    else:
                        fallback_languages += list(
                            mt_fallbacks.get('default', []))
                else:
                    fallback_languages += list(mt_fallbacks)

            for lang in fallback_languages:
                field_name = build_localized_fieldname('slug', lang)
                try:
                    lookup = kwargs.copy()
                    lookup.update({field_name: slug})
                    return article_class.objects.get(**lookup)
                except article_class.DoesNotExist:
                    pass

        # Not found
        raise article_class.DoesNotExist()
Ejemplo n.º 9
0
def get_article(slug, current_lang=None, force_lang=None, all_langs=False, **kwargs):
    """get article"""

    article_class = get_article_class()
    try:
        return article_class.objects.get(slug=slug, **kwargs)
    except article_class.DoesNotExist:
        # if modeltranslation is installed,
        # if no article correspond to the current language article
        # try to look for slug in default language
        if is_localized():

            from modeltranslation import settings as mt_settings
            from modeltranslation.utils import build_localized_fieldname

            fallback_languages = []
            if current_lang:
                fallback_languages += [current_lang, ]
            if force_lang:
                fallback_languages += [force_lang, ]

            mt_fallbacks = getattr(settings, 'MODELTRANSLATION_FALLBACK_LANGUAGES', None)
            if mt_fallbacks is None:
                fallback_languages += [mt_settings.DEFAULT_LANGUAGE, ]
            else:
                if isinstance(mt_fallbacks, dict):
                    if current_lang in mt_fallbacks:
                        fallback_languages += list(mt_fallbacks[current_lang])
                    else:
                        fallback_languages += list(mt_fallbacks.get('default', []))
                else:
                    fallback_languages += list(mt_fallbacks)

            for lang in fallback_languages:
                field_name = build_localized_fieldname('slug', lang)
                try:
                    lookup = kwargs.copy()
                    lookup.update({field_name: slug})
                    return article_class.objects.get(**lookup)
                except article_class.DoesNotExist:
                    pass

        # Not found
        raise article_class.DoesNotExist()
Ejemplo n.º 10
0
    def __init__(self, *args, **kwargs):
        super(BaseArticleAdminForm, self).__init__(*args, **kwargs)  # pylint: disable=E1002
        self.article = kwargs.get('instance', None)
        templates = get_article_templates(self.article, getattr(self, "current_user", None))
        if templates:
            self.fields['template'].widget = forms.Select(choices=templates)

        self.slug_fields = []
        if is_localized():
            for lang_and_name in settings.LANGUAGES:
                from modeltranslation.utils import build_localized_fieldname
                field_name = build_localized_fieldname('slug', lang_and_name[0])
                self.slug_fields.append(field_name)
        else:
            self.slug_fields = ['slug']

        can_change_article_slug = can_rewrite_url()

        if not can_change_article_slug:
            can_change_article_slug = (self.article.publication != BaseArticle.PUBLISHED) if self.article else True

        for slug_field in self.slug_fields:
            if not can_change_article_slug:
                self.fields[slug_field].widget = ReadOnlyInput()
Ejemplo n.º 11
0
 def test_slug_edition_published_can_edit(self):
     settings.COOP_CMS_CAN_EDIT_ARTICLE_SLUG = True
     
     self._log_as_staff_editor()
     
     article_class = get_article_class()
     
     article = mommy.make(article_class, slug="test", publication=BaseArticle.PUBLISHED)
     
     view_name = 'admin:%s_%s_change' % (get_model_app(article_class), get_model_name(article_class))
     url = reverse(view_name, args=[article.id])
     
     response = self.client.get(url)
     
     self.assertEqual(200, response.status_code)
     soup = BeautifulSoup(response.content)
     
     if is_localized():
         from modeltranslation.utils import build_localized_fieldname
         for (lang, _name) in settings.LANGUAGES:
             field_name = build_localized_fieldname('slug', lang)
             self.assertEqual(soup.select("#id_" + field_name)[0]["type"], "text")
     else:
         self.assertEqual(soup.select("#id_slug")[0]["type"], "text")
Ejemplo n.º 12
0
def switch_language(request, context):
    if request and request.user.is_staff and is_localized():
        url = reverse('coop_cms_switch_language_popup')
        return make_link(url, _('Switch language'), 'fugue/globe-green.png', classes=['colorbox-form', 'icon'])
Ejemplo n.º 13
0
 def _get_localized_slug(self, slug):
     """get localized slug"""
     if is_localized():
         return make_locale_path(slug, get_language())
     return slug
Ejemplo n.º 14
0
class ArticleSlugTestCase(BaseTestCase):
    """test slug"""
    
    def tearDown(self):
        """after each test"""
        super(ArticleSlugTestCase, self).tearDown()
        site1 = Site.objects.all()[0]
        settings.SITE_ID = site1.id
    
    def test_create_article_same_title(self):
        """test slug with duplicated titles"""
        article_class = get_article_class()
        article1 = article_class.objects.create(title="Titre de l'article")
        for number in range(12):
            article2 = article_class.objects.create(title=article1.title)
            self.assertNotEqual(article1.slug, article2.slug)
            self.assertEqual(article1.title, article2.title)
        response = self.client.get(article2.get_absolute_url())
        self.assertEqual(200, response.status_code)
        response = self.client.get(article1.get_absolute_url())
        self.assertEqual(200, response.status_code)
            
    def test_create_article_same_different_sites(self):
        """test slug on different sites"""
        article_class = get_article_class()
        article1 = article_class.objects.create(title="Titre de l'article")
        
        site1 = Site.objects.all()[0]
        site2 = Site.objects.create(domain='hhtp://test2', name="Test2")
        settings.SITE_ID = site2.id
        
        article2 = article_class.objects.create(title=article1.title)
        self.assertNotEqual(article1.slug, article2.slug)
        self.assertEqual(article1.title, article2.title)
        
        response = self.client.get(article1.get_absolute_url())
        self.assertEqual(404, response.status_code)
        
        response = self.client.get(article2.get_absolute_url())
        self.assertEqual(200, response.status_code)
        
        settings.SITE_ID = site1.id
        response = self.client.get(article1.get_absolute_url())
        self.assertEqual(200, response.status_code)
        
    @skipIf(not is_localized() or not is_multilang(), "not localized")
    def test_create_lang(self):
        """test slug with language"""
        
        article_class = get_article_class()
        article1 = article_class.objects.create(title="Titre de l'article")
        article2 = article_class.objects.create(title=article1.title)
        self.assertNotEqual(article1.slug, article2.slug)
        self.assertEqual(article1.title, article2.title)
        
        trans_lang = settings.LANGUAGES[1][0]
            
        setattr(article1, 'title_'+trans_lang, 'This is the title')
        article1.save()
        
        setattr(article2, 'title_'+trans_lang, getattr(article1, 'title_'+trans_lang))
        article2.save()
        
        article1 = article_class.objects.get(id=article1.id)
        article2 = article_class.objects.get(id=article2.id)
        
        self.assertEqual(getattr(article1, 'title_'+trans_lang), getattr(article2, 'title_'+trans_lang))
        self.assertNotEqual(getattr(article1, 'slug_'+trans_lang), getattr(article2, 'slug_'+trans_lang))
        
    def _get_localized_slug(self, slug):
        """get localized slug"""
        if is_localized():
            return make_locale_path(slug, get_language())
        return slug
    
    def test_create_article_html_in_title(self):
        """create article with html tag in title"""
        article_class = get_article_class()
        article1 = article_class.objects.create(title="<h1>Titre de l'article</h1>")
        response = self.client.get(article1.get_absolute_url())
        self.assertEqual(200, response.status_code)
        
        expected_title = self._get_localized_slug("/titre-de-larticle/")
        self.assertEqual(article1.get_absolute_url(), expected_title)
        
    def test_create_article_complex_html_in_title(self):
        """create article with html tag in title"""
        article_class = get_article_class()
        article1 = article_class.objects.create(title="<p><h2>Titre de <b>l'article</b><h2><div></div></p>")
        response = self.client.get(article1.get_absolute_url())
        self.assertEqual(200, response.status_code)
        expected_title = self._get_localized_slug("/titre-de-larticle/")
        self.assertEqual(article1.get_absolute_url(), expected_title)

    @override_settings(LANGUAGE_CODE='ru', LANGUAGES=(('ru', 'Russian'), ))
    def create_article_non_ascii_char(self):
        """create an article with russian characters"""
        title = "Миниальбом"
        article_class = get_article_class()
        article1 = article_class.objects.create(title=title)
        response = self.client.get(article1.get_absolute_url())
        self.assertEqual(200, response.status_code)
Ejemplo n.º 15
0
class ArticleTemplateTagsTest(BaseTestCase):
    """Tes article related tags"""
    def _request(self):
        """return a request"""
        class DummyRequest(object):
            """a dummy request"""
            def __init__(self):
                """constructor"""
                self.LANGUAGE_CODE = settings.LANGUAGES[0][0]  # pylint: disable=C0103

        return DummyRequest()

    def test_link_new(self):
        """text article_link tag when article doesn't exist"""
        tpl = Template('{% load coop_utils %}{% article_link "test" %}')
        tpl.render(Context({'request': self._request()}))

        article_class = get_article_class()
        self.assertEqual(article_class.objects.count(), 1)
        article = article_class.objects.all()[0]
        self.assertEqual(article.slug, "test")

    def test_link_existing(self):
        """text article_link tag when article exists"""

        article_class = get_article_class()

        article_class.objects.create(slug="test", title="Test")

        tpl = Template('{% load coop_utils %}{% article_link "test" %}')
        tpl.render(Context({'request': self._request()}))

        self.assertEqual(article_class.objects.count(), 1)
        article = article_class.objects.all()[0]
        self.assertEqual(article.slug, "test")

    @skipIf(len(settings.LANGUAGES) == 0, "not languages")
    def test_link_language(self):
        """text article_link tag when article in multi-language mode"""

        lang = settings.LANGUAGES[0][0]

        tpl = Template('{% load coop_utils %}{% article_link "test" ' + lang +
                       ' %}')
        tpl.render(Context({'request': self._request()}))

        article_class = get_article_class()
        self.assertEqual(article_class.objects.count(), 1)
        article = article_class.objects.all()[0]
        self.assertEqual(article.slug, "test")

    @skipIf(not is_localized() or not is_multilang(), "not localized")
    def test_link_force_lang(self):
        """text article_link tag when language is forced"""

        lang = settings.LANGUAGES[0][0]

        tpl = Template('{% load coop_utils %}{% article_link "test" ' + lang +
                       ' %}')
        request = self._request()
        request.LANGUAGE_CODE = settings.LANGUAGES[1][0]
        tpl.render(Context({'request': request}))

        article_class = get_article_class()
        self.assertEqual(article_class.objects.count(), 1)
        article = article_class.objects.all()[0]
        self.assertEqual(article.slug, "test")

    @skipIf(not is_localized() or not is_multilang(), "not localized")
    def test_link_existing_force_lang(self):
        """text article_link tag when article exists and language is forced"""

        article_class = get_article_class()

        article = article_class.objects.create(slug="test", title="Test")

        request = self._request()
        lang = request.LANGUAGE_CODE = settings.LANGUAGES[1][0]

        setattr(article, "slug_" + lang, "test_" + lang)
        article.save()

        tpl = Template('{% load coop_utils %}{% article_link "test" ' + lang +
                       ' %}')
        tpl.render(Context({'request': request}))

        self.assertEqual(article_class.objects.count(), 1)
        article = article_class.objects.all()[0]
        self.assertEqual(article.slug, "test")
        self.assertEqual(getattr(article, "slug_" + lang), "test_" + lang)

    @skipIf(not is_localized() or not is_multilang(), "not localized")
    def test_link_existing_force_default_lang(self):
        """text article_link tag when language is forced to default"""

        article_class = get_article_class()

        article = article_class.objects.create(title="Test")

        request = self._request()
        def_lang = settings.LANGUAGES[0][0]
        cur_lang = request.LANGUAGE_CODE = settings.LANGUAGES[1][0]

        #activate(cur_lang)
        setattr(article, "slug_" + cur_lang, "test_" + cur_lang)
        article.save()

        count = article_class.objects.count()

        tpl = Template('{% load coop_utils %}{% article_link "test" ' +
                       def_lang + ' %}')
        tpl.render(Context({'request': request}))

        self.assertEqual(article_class.objects.count(), count)
        article = article_class.objects.get(id=article.id)
        self.assertEqual(article.slug, "test")
        self.assertEqual(getattr(article, "slug_" + cur_lang),
                         "test_" + cur_lang)