Sunday, January 1, 2012

Re: Internationalization and localization

I always create multilingual sites. What I do is inspired by django-
modeltranslation, but I find awkward that it leaves a "default"
language field and I prefer to have all my fields defined inside my
models.

1. Create a field for each language and a function that returns the
field corresponding to the client language:

class MyModel(models.Model):
title_ca = models.CharField(max_length=255)
title_en = models.CharField(max_length=255)
title_es = models.CharField(max_length=255)
def title(self):
return getattr(self, 'title_%s' % get_language())

2. In templates call the fuction that detects the language:
{{object.title}}

2. Then, urls.py looks like this:
(r'^$', 'home'),
(r'^(?P<language>\w{2})/$', 'home'),

3. And views.py:

from myapp.utils import enable_language

def home(request, language=None):

# We don't want urls without language prefix in order to prevent
duplicate content
if language is None:
return
HttpResponseRedirect(reverse('isaweb.views.home',kwargs={'language':get_language()}) )

enable_language(request, language)

return render_to_response('home.html',
{},context_instance=RequestContext(request))

4. This goes into utils.py:

def enable_language(request, language):
# Language only gets updated if it changed or is not set.
try:
if request.session['django_language'] != language:
request.session['django_language'] = language
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
except KeyError:
request.session['django_language'] = language
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()


On Dec 7 2011, 3:14 am, kenneth gonsalves <law...@thenilgiris.com>
wrote:
> On Mon, 2011-12-05 at 19:00 -0800, rentgeeen wrote:
> > What I want to how to translate stuff from DB, all at django official
> > say is about static content, what I have only found is this:
>
> django-modeltranslation
> --
> regards
> Kenneth Gonsalves

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment