Skip to content

Instantly share code, notes, and snippets.



Last active Dec 17, 2015
What would you like to do?
Hack to display hvad translated fields in the admin's changelist.
from django.contrib.admin.util import label_for_field
from hvad.admin import TranslatableAdmin as BaseTranslatableAdmin
class TranslatableAdmin(BaseTranslatableAdmin):
Translation friendly admin base class.
Allows user to display translated fields in the admin changelist.
# We make use of a NEW attribute here.
# This is just like list_display except that it accepts translated fields.
# To do so prepend hvad translated fields with "hvad__" like so:
# hvad_list_display = ['hvad__mytranslatedfield', 'normalfield']
# Just like in list_display the fields are listed in the way they are defined.
hvad_list_display = []
# Here we identify the string that will be used to identify translated fields.
hvad_field_prefix = 'hvad__'
def wrap_hvad(self, model_field):
Returns a wrapper that knows how to represent a translated field.
model_field = model_field.split('__')[1]
translation_model = self.model._meta.translations_model
field = translation_model._meta.get_field(model_field)
except FieldDoesNotExist as e:
raise e
def hvad_for_admin(obj):
return obj.lazy_translation_getter(model_field,
hvad_for_admin.short_description = label_for_field(model_field, translation_model)
return hvad_for_admin
def get_list_display(self, request):
Return a sequence containing the fields to be displayed on the
changelist by wrapping the fields in self.hvad_list_display that starts with the prefix defined in
fields = [self.wrap_hvad(field_name) if field_name.startswith(self.hvad_field_prefix) else field_name
for field_name in self.hvad_list_display]
return fields
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment