Django multilingual - how to preview content from any language?
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开发者_如何学JAVA there an easy way to try to get the English title and then check for a title in any other language just for preview?
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
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.
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 :)
精彩评论