djangocms-blog icon indicating copy to clipboard operation
djangocms-blog copied to clipboard

"View on site" in django admin does not take into account absence of translation

Open petrklus opened this issue 7 years ago • 1 comments

Scenario:

  • Admin language in EN
  • Available languages are EN, DE
  • Post is created with DE translation ONLY

In the scenario above, the "View on site" URL links to a 404 page. The reason for this is that Post's get_absolute_url does not check for current language (which is what the reverse function does).

See below for a monkey-patch fix:

from django.utils.translation import get_language, ugettext, ugettext_lazy as _
from parler.utils.context import switch_language
from djangocms_blog.settings import get_setting
from django.utils import translation

def monkey_get_absolute_url(self, lang=None):
    if not lang or lang not in self.get_available_languages():
        lang = get_language()
    if not lang or lang not in self.get_available_languages():
        lang = self.get_current_language()
    with switch_language(self, lang):
        category = self.categories.first()
        kwargs = {}
        if self.date_published:
            current_date = self.date_published
        else:
            current_date = self.date_created
        urlconf = get_setting('PERMALINK_URLS')[self.app_config.url_patterns]
        if '<year>' in urlconf:
            kwargs['year'] = current_date.year
        if '<month>' in urlconf:
            kwargs['month'] = '%02d' % current_date.month
        if '<day>' in urlconf:
            kwargs['day'] = '%02d' % current_date.day
        if '<slug>' in urlconf:
            kwargs['slug'] = self.safe_translation_getter(
                'slug', language_code=lang, any_language=True
            )  # NOQA
        if '<category>' in urlconf:
            kwargs['category'] = category.safe_translation_getter(
                'slug', language_code=lang, any_language=True)  # NOQA

        request_language = translation.get_language()
        try:
            if lang not in self.get_available_languages():
                # print "Switching language - as it's not valid"
                lang = self.get_available_languages()[0]
                translation.activate(lang)
            link = reverse('%s:post-detail' % self.app_config.namespace, kwargs=kwargs)
        finally:
            # clean up
            translation.activate(request_language)

        return link

from djangocms_blog.models import Post
Post.get_absolute_url = monkey_get_absolute_url```

petrklus avatar Oct 17 '18 10:10 petrklus

@petrklus thanks for spotting it! would be able to contribute the fix as PR? In case, please open against release/0.9 branch

Thanks!

yakky avatar Nov 10 '18 12:11 yakky