0

I am new to django and i am loving it so far especially its nice community. Here is my question: I have this model

class Nationality(models.Model):
  nationality_fr = models.CharField(max_length=50)
  nationality_en = models.CharField(max_length=50)
  show_flag = models.BooleanField()
  display_order = models.PositiveSmallIntegerField()

  def __str__(self):
    return self.nationality_fr

I want to change the __ str __ function to return nationality_fr if the language selected (by the user) is "fr" and language_en if the selected language is "en". the reason i need this is because i am showing a drop-down for selecting nationalities for the user to choose and he/she should see the choices in his/her language. what is the best to way to deal with this?

Note: I know there is a nice app for countries but i should be able to do that for other scenarios other than this countries scenario.

John-Silver
  • 35
  • 1
  • 7
  • Just out of curiosity, what do you actually store in the two nationality fields? (What I'm eluding to is why don't you just use the internationalization methods?) – Sayse May 06 '16 at 20:45
  • hi @Sayse, nice hearing from u again. i will store the name of the country in English and in French. can u elaborate please on how to use i18n methods to solve this? – John-Silver May 06 '16 at 20:58

2 Answers2

0

The simplest method is get_language(), that tells you the language in the current thread based on settings.LANGUAGE_CODE setting.

from django.utils.translation import get_language

def __str__(self):
    if get_language().startswith('fr'):
        return self.nationality_fr
    else:
        return self.nationality_en

If you let Django set the language dynamically, based on request parameters like URL substring or browser header, use django.utils.translation.get_language_from_request instead (since Django 1.8). See docs here

C14L
  • 12,153
  • 4
  • 39
  • 52
  • yeah i want to use the language from request not from settings. now the problem is how would i get a hold of the request from within the model definition? – John-Silver May 06 '16 at 22:27
0

After some research, i found the solution: django.utils.translation.get_language(). It returns the language used in the current thread and u can use it in models like so:

from django.utils import translation

@property
def nationality(self):
    lang = translation.get_language()
    if lang == "fr":
        return self.nationality_fr
    else:
        return self.nationality_en

def __str__(self):
    return self.nationality
Community
  • 1
  • 1
John-Silver
  • 35
  • 1
  • 7