[Django]-Database localization in Django

0👍

I can see two method for doing this, one in your view and the other one is in the template…

  1. In view:

Probably you keep the user language information somewhere so,

user_lang = 'es'
obj = Somemodel.objects.get(pk=123434)
obj.local_name = getattr(obj, 'name_%s'%user_lang)

So, you keep local translation in a specific variable of the instance and in your template you can use is as:

{{obj.local_name}}

But that might be costly if you wish to pass the template a queryset instead of a single instance. For a such usege you have to evaluate that value for each object in your queryset.

  1. In template:

That is a more complex way of solving the porblem in the template…

Define a template tag and pass object_id, and local language information and get the translated text using a similar getattr function. But in that point, if you wish to use this for more than one model, you probably have to pass a content type information for your template tag too, such as:

{% get_translation <object_id> <content_type_id> <local_language> %}

And in your template tag function, do something like:

from django.contrib.contenttypes.models import ContentType

....
cont_obj = Content_type.objects.get_for_id(<cotent_type_id>) #get the related model 
obj = cont_obj.get_object_for_this_type(pk=<object_id>) # get your object 
return getattr(obj, 'name_%s'%<local_language>)
👤Mp0int

3👍

You should look at http://goodcode.io/articles/django-multilanguage/ Here’s a simple solution that may fit your use case and is easy to implement and understand.

1👍

You should look at Django Transmeta, it work the same way as what you’ve done (DB fields with language code) but it’s a more complete solution. It already deal with the template stuff, etc.

You can check Model Internationalization and Django Packages for more info and ideas in this domain.

Leave a comment