1. Carl Meyer
  2. django-modeltranslation

Commits

eschler  committed 38d42e8

Fixed creation of db fields with invalid python language code, resolving #4 (thanks to carl.j.meyer).

  • Participants
  • Parent commits 918b324
  • Branches default

Comments (0)

Files changed (2)

File modeltranslation/fields.py

View file
  • Ignore whitespace
     
 from django.conf import settings
 from django.db.models.fields import Field, CharField
-from django.utils.translation import get_language
 
-from modeltranslation.utils import build_localized_fieldname
+from modeltranslation.utils import get_language, build_localized_fieldname
 
 class TranslationField(Field):
     """
     #def __contains__(self, model):
         #return model in self.__class__._registry
     
-        
+        

File modeltranslation/utils.py

View file
  • Ignore whitespace
 from django.conf import settings
 from django.core.exceptions import ValidationError
 from django.contrib.contenttypes.models import ContentType
-from django.utils.translation import get_language
+from django.utils.translation import get_language as _get_language
+
+def get_language():
+    """
+    Return an active language code that is guaranteed to be in
+    settings.LANGUAGES (Django does not seem to guarantee this for
+    us.)
+    
+    """
+    lang = _get_language()
+    available_languages = [l[0] for l in settings.LANGUAGES]
+    if lang not in available_languages and '-' in lang:
+        lang = lang.split('-')[0]
+    if lang in available_languages:
+        return lang
+    return available_languages[0]
 
 class TranslationFieldDescriptor(object):
     """
 
     def __set__(self, instance, value):                
         # print "Descriptor.__set__%s %s %s.%s: %s" % (id(instance), id(self), type(instance), self.name, value)
-        lang = get_language()              
+        lang = get_language()
         loc_field_name = build_localized_fieldname(self.name, lang)
         
         # also update the translation field of the current language        
         
 
 def build_localized_fieldname(field_name, lang):
-    return '%s_%s' % (field_name, lang)
+    return '%s_%s' % (field_name, lang.replace('-', '_'))