Question

I've watched many solutions for working with models in multilanguage. But none of them it's easy enough to apply, including that doesn't work with south. The apps that I watched was obtained from:

Well, I try a solution for my own with KISS (Keep It simple Stupid) in mind and this is my analysis and solution, based on my specific needs (Only two languages, Spanish as default language):

  1. I can create the fields from specific language because I will work only with english and spanish, and it's pretty straightforward

    class Country(models.Model):
        name = models.CharField('Pais', max_length=80)
        name_en = models.CharField('Country', max_length=80, blank=True, null=True)
    
        class Meta:
            verbose_name = 'Pais'
            verbose_name_plural = 'Paises'
    
        def __unicode__(self):
            return self.name
    
  2. I can create a custom template tag that give me the desired field:

    @register.tag(name='get_model_translate')
        def do_translation(parser, token):
            try:
                tag_name, o_model, field = token.split_contents()
            except ValueError:
                raise template.TemplateSintaxError(u'Los parámetros no son válidos')
    
            return Translate(tag_name, o_model, field)
    
    class Translate(template.Node):
    
        def __init__(self, tag_name, o_model, field):
            self.tag_name = tag_name
            self.o_model = template.Variable(o_model)
            self.field = field
    
        def render(self, context):
            lang_code = context.get('request').LANGUAGE_CODE
    
            o_model = self.o_model.resolve(context)
            try:
                data = o_model.__getattribute__('%s_%s' % (self.field, lang_code))
            except Exception, e:
                try:
                    data = o_model.__getattribute__('%s' % self.field)
                except Exception, e:
                    data = ''
    
            return data
    
  3. I can pass the desired data from the view to the template

    response['country'] = Country.objects.get(pk=1)
    
  4. And I can call it like this, asumming that I have the LANGUAGE_CODE in my request context:

    {% get_model_translate country name %}
    

So, my question is: ¿Is this a good approach? I think that the only problem that I see is a performance one, but I'm not pretty sure about that, looking for the solutions that others have done.

Thanks for any advise

Was it helpful?

Solution

I have worked on many multilanguage projects with the following: https://github.com/deschler/django-modeltranslation Works really good for model translations, no need to hack your models to get it working and finally works with South.

OTHER TIPS

Django-hvad is a good library for this purpose.

Also you may have a look at the approach used here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top