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?
The following answer assumes that you are using the admin system to auto-generate
slug
fromtitle
. This may or may not be your exact situation but it may be relevant.This is an extension of the explanation within the Django-hvad project pages.
The way to implement your feature is within the the
admin.py
file within your app. You need to extend the__init__()
method of theTranslatableAdmin
class.Say, for example, your model is called
Entry
. The simplified code inmodels.py
could be along the lines of the following:Your corresponding
admin.py
file should then be as follows: