django-hvad - how should I set a translated field value while saving a model instance? -


background: use django-hvad , have translatablemodel. in translatedfields have slug attribute should automatically created using title attribute while saving model.

problem: difficult set value of 1 of translatedfields while saving instance. solution works override save_translations method of translatablemodel follows. second last line differs original:

    @classmethod     def save_translations(cls, instance, **kwargs):         """         following copied pasted 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             # following line different original.             trans.slug = defaultfilters.slugify(trans.title)             trans.save() 

this solution not nice, because makes use of copy , paste. there better way achieve same?

the following answer assumes using admin system auto-generate slug title. may or may not exact situation may relevant.

this extension of explanation within django-hvad project pages.

the way implement feature within the admin.py file within app. need extend __init__() method of translatableadmin class.

say, example, model called entry. simplified code in models.py along lines of following:

from django.db import models 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') 

your corresponding admin.py file should follows:

from django.contrib import admin  hvad.admin import translatableadmin  .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) 

Comments