|
| 1 | +from typing import Dict, Optional, Union |
| 2 | + |
| 3 | +from django.conf import settings |
| 4 | +from django.db.utils import IntegrityError |
| 5 | + |
| 6 | +from ..forms import LocalizedBooleanFieldForm |
| 7 | +from ..value import LocalizedBooleanValue, LocalizedValue |
| 8 | +from .field import LocalizedField |
| 9 | + |
| 10 | + |
| 11 | +class LocalizedBooleanField(LocalizedField): |
| 12 | + """Stores booleans as a localized value.""" |
| 13 | + |
| 14 | + attr_class = LocalizedBooleanValue |
| 15 | + |
| 16 | + @classmethod |
| 17 | + def from_db_value(cls, value, *_) -> Optional[LocalizedBooleanValue]: |
| 18 | + db_value = super().from_db_value(value) |
| 19 | + |
| 20 | + if db_value is None: |
| 21 | + return db_value |
| 22 | + |
| 23 | + if isinstance(db_value, str): |
| 24 | + if db_value.lower() == "true": |
| 25 | + return True |
| 26 | + return False |
| 27 | + |
| 28 | + if not isinstance(db_value, LocalizedValue): |
| 29 | + return db_value |
| 30 | + |
| 31 | + return cls._convert_localized_value(db_value) |
| 32 | + |
| 33 | + def to_python( |
| 34 | + self, value: Union[Dict[str, str], str, None] |
| 35 | + ) -> LocalizedBooleanValue: |
| 36 | + """Converts the value from a database value into a Python value.""" |
| 37 | + |
| 38 | + db_value = super().to_python(value) |
| 39 | + return self._convert_localized_value(db_value) |
| 40 | + |
| 41 | + def get_prep_value(self, value: LocalizedBooleanValue) -> dict: |
| 42 | + """Gets the value in a format to store into the database.""" |
| 43 | + |
| 44 | + # apply default values |
| 45 | + default_values = LocalizedBooleanValue(self.default) |
| 46 | + if isinstance(value, LocalizedBooleanValue): |
| 47 | + for lang_code, _ in settings.LANGUAGES: |
| 48 | + local_value = value.get(lang_code) |
| 49 | + if local_value is None: |
| 50 | + value.set(lang_code, default_values.get(lang_code, None)) |
| 51 | + |
| 52 | + prepped_value = super().get_prep_value(value) |
| 53 | + if prepped_value is None: |
| 54 | + return None |
| 55 | + |
| 56 | + # make sure all values are proper values to be converted to bool |
| 57 | + for lang_code, _ in settings.LANGUAGES: |
| 58 | + local_value = prepped_value[lang_code] |
| 59 | + |
| 60 | + if local_value is not None and local_value.lower() not in ( |
| 61 | + "false", |
| 62 | + "true", |
| 63 | + ): |
| 64 | + raise IntegrityError( |
| 65 | + 'non-boolean value in column "%s.%s" violates ' |
| 66 | + "boolean constraint" % (self.name, lang_code) |
| 67 | + ) |
| 68 | + |
| 69 | + # convert to a string before saving because the underlying |
| 70 | + # type is hstore, which only accept strings |
| 71 | + prepped_value[lang_code] = ( |
| 72 | + str(local_value) if local_value is not None else None |
| 73 | + ) |
| 74 | + |
| 75 | + return prepped_value |
| 76 | + |
| 77 | + def formfield(self, **kwargs): |
| 78 | + """Gets the form field associated with this field.""" |
| 79 | + defaults = {"form_class": LocalizedBooleanFieldForm} |
| 80 | + |
| 81 | + defaults.update(kwargs) |
| 82 | + return super().formfield(**defaults) |
| 83 | + |
| 84 | + @staticmethod |
| 85 | + def _convert_localized_value( |
| 86 | + value: LocalizedValue, |
| 87 | + ) -> LocalizedBooleanValue: |
| 88 | + """Converts from :see:LocalizedValue to :see:LocalizedBooleanValue.""" |
| 89 | + |
| 90 | + integer_values = {} |
| 91 | + for lang_code, _ in settings.LANGUAGES: |
| 92 | + local_value = value.get(lang_code, None) |
| 93 | + |
| 94 | + if isinstance(local_value, str): |
| 95 | + if local_value.lower() == "false": |
| 96 | + local_value = False |
| 97 | + elif local_value.lower() == "true": |
| 98 | + local_value = True |
| 99 | + else: |
| 100 | + raise ValueError( |
| 101 | + f"Could not convert value {local_value} to boolean." |
| 102 | + ) |
| 103 | + |
| 104 | + integer_values[lang_code] = local_value |
| 105 | + elif local_value is not None: |
| 106 | + raise TypeError( |
| 107 | + f"Expected value of type str instead of {type(local_value)}." |
| 108 | + ) |
| 109 | + |
| 110 | + return LocalizedBooleanValue(integer_values) |
0 commit comments