I’m working in a bilingual project (es/en); for this project I’ve chosen to use django’s i18n internationalization system (and I’m starting to regret it…)
Today’s problem is the following:
for some models, my database stores information like description and es_description, or english_common_name and spanish_common_name (these are attributes of my objects, and are used in many circumstances, not only for page-translation issues).
A sample model can be defined like:
def MyModel(models.Model):
name = ...
type = ...
authors = ...
contributors = ...
...
...
description = models.TextField(max_length = 800, blank=True)
es_description = models.TextField(max_length = 800, blank=True)
...
english_common_name = models.CharField('name', max_length=80, unique=True)
spanish_common_name = models.CharField('nombre', max_length=80, unique=True)
...
Let’s say I want to retrieve this information in my template, according to lang, the language selected by the user.
For example, in some place of my template I could have something like
<h1>{{name}}</h1>
<h3>{{english_common_name}}</h3>
<p>{{description}}</p>
<p>{% trans "Contributors" %}: {{contributors}}</p>
How can I call {{spanish_common_name}} instead of {{english_common_name}} or {{es_description}} instead of {{description}} if the page language is set to 'es'?
I absolutely refuse to do something like
<p>{% ifequal lang 'es' %}{{descrpition}}{% else %}{{es_description}}{% endifequal %}</p>
And if I try to manage this in views… I don’t want to define a get_translated_content function like this
def get_translated_content(en_content,es_content,lang):
if lang is 'es':
return es_content
else:
return en_content
...
# MyView
...
return render_to_response(...,
{'object': my_object,
'object_common_name': get_translated_content(english_common_name, spanish_common_name, lang),
'object_description': get_translated_content(description, es_description, lang),
... ,})
This could work (still being an horrible solution) in simple situations, but in more complex cases I would be forced to return dictionaries which are localized copies of the original MyModel object (and if in a view I have to use lots of different instances of the same model, I would be forced to generate a biiiig list of these dictionaries).
Please, tell me that there is a good, logic way to access db object-fields according to the page’s language, please!
Edit: after reading the answers received so far, I think I should add to my question a “leaving the database structure (almost) unchanged” clause.
You really should use something like django-multilingual (if you’re using Django 1.2, see Django 1.2 compatible branch).
For your example (based on the documentation)
Accessing translatable fields
The current language is deteced the same way django detects it.