5

Background: I use django-hvad and have a TranslatableModel. In its TranslatedFields I have a slug attribute which should be automatically created using the title attribute while saving the model.

Problem: It is difficult to set the value of one of the TranslatedFields while saving the instance. A solution that works is to override the save_translations method of my TranslatableModel as follows. Only the second last line differs from the original:

    @classmethod
    def save_translations(cls, instance, **kwargs):
        """
        The following is copied an pasted from the TranslatableModel class.
        """
        opts = cls._meta
        if hasattr(instance, opts.translations_cache):
            trans = getattr(instance, opts.translations_cache)
            if not trans.master_id:
                trans.master = instance
            # The following line is different from the original.
            trans.slug = defaultfilters.slugify(trans.title)
            trans.save()

This solution is not nice, because it makes use of copy and paste. Is there a better way to achieve the same?

4

2 回答 2

6

以下答案假设您使用管理系统slugtitle. 这可能是也可能不是您的确切情况,但它可能是相关的。

这是Django-hvad 项目页面中解释的扩展。

实现您的功能的方法是admin.py在您的应用程序内的文件中。您需要扩展类的__init__()方法TranslatableAdmin

比如说,你的模型叫做Entry. 中的简化代码models.py可能如下所示:

from django.db import models
from hvad.models import TranslatableModel, TranslatedFields

class Entry(TranslatableModel):
    translations = TranslatedFields(
        title=models.CharField(max_length=100,),
        slug=models.SlugField(),
        meta={'unique_together': [('language_code', 'slug')]},
    )
    def __unicode__(self):
        return self.lazy_translation_getter('title')

您的相应admin.py文件应如下所示:

from django.contrib import admin

from hvad.admin import TranslatableAdmin

from .models import Entry

class EntryAdmin(TranslatableAdmin):
    def __init__(self, *args, **kwargs):
        super(EntryAdmin, self).__init__(*args, **kwargs)
        self.prepopulated_fields = {'slug': ('title',)}

admin.site.register(Entry, EntryAdmin)
于 2013-08-02T21:31:00.337 回答
0

使用 django-hvad 1.5.0。

用例:在 Django Admin 之外设置 TranslatableModel 字段的值。

# self is a TranslatableModel instance with `translations`
# this first line will initialize the cache if necessary
slug = self.lazy_translation_getter('slug')
translation = get_cached_translation(self)
translation.master = self
translation.slug = defaultfilters.slugify(self.title)  # whatever value
translation.save()
于 2016-04-28T16:14:14.870 回答