Question

Is there a way for __unicode__ to return spanish or english depending on request.session['django_language']? Should I be designing my models differently or is this the standard way of doing things?

class Tip(models.Model):
    '''A small random tip for users to see on the login page'''
    en_text = models.CharField(max_length=500)
    es_text = models.CharField(max_length=500)

    def __unicode__(self):
        pass

And then from the view to the template...

try:
    tip = Tip.objects.order_by('?')[0]
except:
    tip = None

-->

<p>{{ tip }}</p>
Was it helpful?

Solution

I'm not sure that this is the greatest way to do it, but I faced a similar situation and did the following:

class Image(models.Model, TranslatedModelMixin):
     artifact = models.ForeignKey(Artifact)
     caption = models.CharField(max_length=500, null=True, blank=True)
     caption_fr = models.CharField(max_length=500, null=True, blank=True)
     image = models.ImageField(upload_to='artifacts/images')

     language_code = 'en'
     translated_fields = ['caption']

     def __unicode__(self):
         return u'Image for %s' % self.artifact.name


 class TranslatedModelMixin(object):
     """
     Given a translated model, overwrites the original language with
     the one requested
     """

     def set_language(self, language_code):
         if language_code == 'en':
             return

         self.language_code = language_code

         for field in self.translated_fields:
             translated_field_key = field + '_' + language_code
             translated_field = getattr(self, translated_field_key)
             setattr(self, field, translated_field)

         return

So if I want the model data in french, I just do image.set_language('fr') and then in my template I can just do {{ image.caption }} and get the translated version. I wouldn't use __unicode__ to present the model in the template.

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