Aug 14 2010

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:

def get_local_str_or_other(obj, field_name):
    result = getattr(obj, field_name)
    if result:
        return result
    else:
        field_for_search = field_name + "_"
        translations = [getattr(obj, field_for_search + lang[0].replace("-","_")) for lang in settings.LANGUAGES]
        for translation in translations:
            if translation != None:
                return unicode(translation)
 

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:

def __unicode__(self):
        return get_local_str_or_other(self, "title")
 

 

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
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

Related posts:

  1. Django translations: multilingual, i18n, app names

1 Comment

  • By Jacinda Wernicki, August 17, 2011 @ 1:50 pm

    Fantastic site. Plenty of helpful information here. I am sending it to several friends ans also sharing in delicious. And obviously, thanks for your sweat, Generally I do not learn article on blogs, but I wish to say that this write-up very pressured me to try and do so! Your writing style has been surprised me. Thank you, very great post.

Other Links to this Post

RSS feed for comments on this post. TrackBack URI

Leave a comment

WordPress Themes