pythondjangodjango-taggitdjango-parler

Tags are not being saved when using django-parler


I am using django-parler for translation and django-taggit for adding tags. But when I add tags inside translation field (because of using in multiple language) tags are not being saved in admin page.
models.py

class News(models.Model):
    translations = TranslatedFields(
        title=models.CharField(max_length=255),
        content=RichTextUploadingField(),
        tags=TaggableManager(),
        slug=models.SlugField(max_length=255, db_index=True),
    )
    category = models.ForeignKey(Category)

Solution

  • In this example, tags are being added in admin's save_method(). First, you need to fetch translations related to that obj, then iterate translation objects to add tags. Tags come with obj when you save it in admin page.

    from taggit.models import Tag
    
    def save_model(self, request, obj, change):
        translations = obj.translations.all()
        for translation in translations:
            tags = []
            for tag_name in obj.tags:
                if translation.language_code == "uz":
                    tag_name = to_latin(tag_name)
                elif translation.language_code == "uz-cyril":
                    tag_name = to_cyrillic(tag_name)
                    tag, created = Tag.objects.get_or_create(name=tag_name)
                    tags.append(tag)
            translation.tags.set(tags)