简体   繁体   English

保存Django modeltranslation的翻译后段不起作用

[英]Saving translated slug of django modeltranslation not working

I've been breaking my head over this for a day now. 我已经为此烦恼了一天。

I use django-modeltranslation to translate blog-like posts. 我使用django-modeltranslation翻译类似博客的帖子。 All works fine, except I also try to automatically translate the slugs from the title, based off of this article: https://raphaelbeck.wordpress.com/2011/04/16/how-to-translate-slug-with-django-modeltranslation/ 一切正常,除了我也尝试根据本文自动翻译标题中的子弹: https : //raphaelbeck.wordpress.com/2011/04/16/how-to-translate-slug-with-django -modeltranslation /

Only the translated slug is not translated saved to the database. 仅翻译的子弹未翻译,保存到数据库。

class Item(models.Model):
    category = models.ForeignKey(
        'help.category',
        on_delete=models.PROTECT,
        related_name='categories')
    title = models.CharField(_('Titel'),max_length=255)
    description = RichTextField(_('Omschrijving'))
    slug = AutoSlugField(_('slug'), populate_from='title', overwrite=True)

    class Meta:
        verbose_name = _(u"Item") 
        verbose_name_plural = _(u"Items")

        #automatically creating slugs for translations
    def save(self, *args, **kwargs):
        for lang_code, lang_verbose in settings.LANGUAGES:
            if hasattr(self, 'slug_%s' % lang_code) and hasattr(self, 'title_%s' % lang_code):
                setattr(self, 'slug_%s' % lang_code, slugify(getattr(self, 'title_%s' % lang_code, u"")))
            print(self.slug_nl)
            print(self.slug_en)

        print(self.slug_nl)
        print(self.slug_en)
        super().save(*args, **kwargs)

    def __str__(self):
        return str(self.title)

I added some print funtions to see what actually happens. 我添加了一些打印功能,以查看实际发生的情况。 The console logs are as expected: 控制台日志符合预期:

dutch-slug 荷兰蛞蝓

None 没有

dutch-slug 荷兰蛞蝓

english-slug 英语,蛞蝓

dutch-slug 荷兰蛞蝓

english-slug 英语,蛞蝓

-> slug_en is translated correctly based on the title in the console, but in the database the dutch slugs are saved. -> slug_en是根据控制台中的标题正确翻译的,但是荷兰的slug被保存在数据库中。

Thanks in advance! 提前致谢! Any ideas are greatly appreciated. 任何想法都将不胜感激。

django-model-translation and AutoSlugField perform what they need to do during the save() method, so what you do prior to saving is overwritten later. django-model-translation和AutoSlugFieldsave()方法期间执行其所需的操作,因此save()之前所做的操作稍后会被覆盖。

There's no other way than to add the translations post-save, even if that means saving the model twice. 除了保存后添加翻译,没有其他方法,即使那意味着要两次保存模型。 Also you can't call save() in post_save otherwise you create an endless recursion. 另外,您不能在post_save中调用save() ,否则会创建无限递归。 Use update() on the queryset. 在查询集上使用update() Write a post_save signal handler: 编写一个post_save信号处理程序:

@receiver(post_save, sender=Item)
def add_slug_translations(instance, **kwargs):
    attrs = {}
    for lang_code, lang_verbose in settings.LANGUAGES:
        if hasattr(self, 'slug_%s' % lang_code) and hasattr(self, 'title_%s' % lang_code) and getattr(self, 'title_%s' % lang_code):
            attrs.update({'slug_%s' % lang_code: slugify(getattr(self, 'title_%s' % lang_code, u"")})
    if attrs:
        Item.objects.filter(id=instance.id).update(**attrs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM