Skip to content

Commit a0ca977

Browse files
author
Adrian Muntean
committed
Set None in case the LocalizedIntegerField is null
In case the LocalizedIntegerField is null in the DB then it must explicitly be set to None, otherwise it will yield TypeError: __str__ returned non-string
1 parent eb2cb6b commit a0ca977

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

README.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -279,7 +279,7 @@ Besides ``LocalizedField``, there's also:
279279

280280
Allows storing integers in multiple languages. This works exactly like ``LocalizedField`` except that
281281
all values must be integers. Do note that values are stored as strings in your database because
282-
the backing field type is ``hstore``, which only allows storing integers. The ``LocalizedIntegerField``
282+
the backing field type is ``hstore``, which only allows storing strings. The ``LocalizedIntegerField``
283283
takes care of ensuring that all values are integers and converts the stored strings back to integers
284284
when retrieving them from the database. Do not expect to be able to do queries such as:
285285

localized_fields/widgets.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from django import forms
77
from django.contrib.admin import widgets
88

9-
from .value import LocalizedValue
9+
from .value import LocalizedValue, LocalizedIntegerValue
1010

1111

1212
class LocalizedFieldWidget(forms.MultiWidget):
@@ -52,6 +52,7 @@ def decompress(self, value: LocalizedValue) -> List[str]:
5252
return result
5353

5454
def get_context(self, name, value, attrs):
55+
value = self.remove_if_needed(value)
5556
context = super(forms.MultiWidget, self).get_context(name, value, attrs)
5657
if self.is_localized:
5758
for widget in self.widgets:
@@ -98,6 +99,16 @@ def build_widget_attrs(widget, value, attrs):
9899

99100
return attrs
100101

102+
@staticmethod
103+
def remove_if_needed(value):
104+
"""If the field LocalizedIntegerField is null in the DB then it must
105+
be set to None so it can be represented"""
106+
if isinstance(value, LocalizedIntegerValue):
107+
not_none_score = list(filter(lambda x: value[x] is not None, [i[0] for i in settings.LANGUAGES]))
108+
return value if len(not_none_score) > 0 else None
109+
else:
110+
return value
111+
101112

102113
class LocalizedCharFieldWidget(LocalizedFieldWidget):
103114
"""Widget that has an input box for every language."""

0 commit comments

Comments
 (0)