1

I am writing a get_absolute_url method for a model in Django. This method is later used in building a sitemap. I am trying to form a url, but there is an issue in that I do not know how to get the language argument at the model stage.

That is, the urls in the sitemap end up looking like example.com/news/123, whereas I would like them to look like example.com/en/123.

How can this be done?

class News(models.Model):
    title = models.CharField(_("Название"), max_length=255)
    body = HTMLField(configuration='CKEDITOR_SETTINGS_BODY')
    image = models.ForeignKey(NewsImageModel, on_delete=models.CASCADE)
    background_image = FilerFileField(on_delete=models.SET_NULL, null=True, blank=True)
    created = models.DateTimeField(default=datetime.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    view_count = models.PositiveIntegerField(default=0)

    @property
    def full_name(self):
        return '%s %s' % (self.author.last_name, self.author.first_name)

    @property
    def short_description(self):
        return truncatewords(self.body, 10)

    @property
    def clear_date(self):
        return date(self.created, "d.m.y")

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return "/news/" + str(self.id)

We are using DjangoCMS, so in settings.py, we have something like this:

LANGUAGES = (
    ('ru', gettext("ru")),
    ('en', gettext("en")),
)

CMS_LANGUAGES = {
    'default': {
        'public': True,
        'hide_untranslated': False,
        'redirect_on_fallback': True,
    },


    1: [
        {
            'public': True,
            'code': 'ru',
            'hide_untranslated': False,
            'name': gettext("ru"),
            'redirect_on_fallback': True,

        },
        {
            'public': True,
            'code': 'en',
            'hide_untranslated': False,
            'name': gettext("en"),
            'redirect_on_fallback': True,
        },
    ],
}
MadPhysicist
  • 5,401
  • 11
  • 42
  • 107
  • 1
    this may help you https://stackoverflow.com/questions/3356964/how-can-i-get-the-current-language-in-django – cizario Nov 06 '20 at 17:13

0 Answers0