Tag Archives: translation

Django multilingual: select translation instead of ‘None’

If you use the django-multilingual module for multilingual content, you need to add a translation for every language your entity could be seen through. Otherwise you get 'None' as a title (which is way too blurry and quite indescribable). Thanks to my colleague and friend lpetrov I found a way to pass through this limitation and print any possible translation if the current one is not available.

I've added a translation.py file in my project which I import in all my apps when necessary. Here there is the code:

  1. def get_local_str_or_other(obj, field_name):
  2. result = getattr(obj, field_name)
  3. if result:
  4. return result
  5. else:
  6. field_for_search = field_name + "_"
  7. translations = [getattr(obj, field_for_search + lang[0].replace("-","_")) for lang in settings.LANGUAGES]
  8. for translation in translations:
  9. if translation != None:
  10. return unicode(translation)
  11.  

Later I import the function in my models and I redefine the __unicode__ function. If the name I want to print by default is the field 'title', we have the following:

  1. def __unicode__(self):
  2. return get_local_str_or_other(self, "title")
  3.  

 

del.icio.us Digg DZone Facebook Google Google Reader Magnolia reddit SlashDot Technorati ReadMe.ru Dobavi.com Dao.bg Lubimi.com Ping.bg Pipe.bg Svejo.net Web-bg.com