views:

41

answers:

3

I'm using django-multilingual for a Django based website. When I define the __unicode__ function for a model to return this way:

def __unicode__(self):
        return unicode(self.title)

However my default language is English and I have some items that are inserted in Dutch only. When I preview the full list, I get "None" as a title.

Is there an easy way to try to get the English title and then check for a title in any other language just for preview?

A: 

Well, assuming your model stores the Dutch version in an attribute called dutch_title, you could do this.

def __unicode__(self):
  # If we've got an English title, use that
  if self.title:
    return self.title

  # Otherwise, default to the Dutch title
  return self.dutch_title

Without knowing what you mean by "some items are inserted in Dutch only", it's a bit difficult to answer your question more helpfully.

Dominic Rodger
I have 4 languages with default English. My point is that I could insert description in all the four languages or only one of them. Is there a way to try English and if none, to iterate all the other languages in order to show the inserted data and not "None" literal?
Mario Peshev
A: 

Depending on the app you are using (for example - django-multilingual), you can use:

<td>{{ object.name_en|escape }}</td>

*(example from: http://code.google.com/p/django-multilingual/source/browse/trunk/testproject/templates/articles/category_list.html)*

As i remember there were some other forks of this app, that used to change that behavior like this:

Objec title is: {{object.en.name}}

In case you use other app, you can always run the manage.py shell and test with dir(MyModel), or dir(MyModel.fields) to check what fields are defined there :)

In case there are magic getters for those field names and you cant see anything interesting in dir(...), you can refer to the code of your prefered l18n app and see what going under the hood :)

Lyubomir Petrov
A: 

Iterating over all translations can be easily done like this:

>>> translations = [getattr(obj, "name_" + lang[0].replace("-","_")) for lang in
settings.LANGUAGES]

Where obj is the model object, and lang will represent a tuple ('bg', 'Bulgarian') from your settings file.

lang[0].replace("-","_") is required, in case that you have languages like "uk-gb", because those values are placed into name_uk_gb

Lyubomir Petrov
I'll try to integrate this one in the project and get any content in all the languages, thank you
Mario Peshev