23 lines
766 B
Python
23 lines
766 B
Python
|
from django.conf import settings
|
||
|
from django.db import models
|
||
|
|
||
|
from .validators import LanguageValidator
|
||
|
|
||
|
class LanguageField(models.CharField):
|
||
|
default_validators = [LanguageValidator()]
|
||
|
|
||
|
def __init__(self, *args, **kwargs):
|
||
|
kwargs.setdefault("max_length", 16)
|
||
|
super().__init__(*args, **kwargs)
|
||
|
|
||
|
def pre_save(self, model_instance, add):
|
||
|
value = getattr(model_instance, self.attname, None)
|
||
|
if value:
|
||
|
value = value.lower()
|
||
|
if "_" in value:
|
||
|
lang, country = value.split("_")
|
||
|
value = "_".join([lang, country.upper()])
|
||
|
setattr(model_instance, self.attname, value)
|
||
|
return value
|
||
|
else:
|
||
|
return super().pre_save(model_instance, add)
|