| 1 |
import json |
| 2 |
|
| 3 |
from django import forms |
| 4 |
from django.core.exceptions import ValidationError |
| 5 |
from django.utils.translation import gettext_lazy as _ |
| 6 |
|
| 7 |
__all__ = ["HStoreField"] |
| 8 |
|
| 9 |
|
| 10 |
class HStoreField(forms.CharField): |
| 11 |
""" |
| 12 |
A field for HStore data which accepts dictionary JSON input. |
| 13 |
""" |
| 14 |
|
| 15 |
widget = forms.Textarea |
| 16 |
default_error_messages = { |
| 17 |
"invalid_json": _("Could not load JSON data."), |
| 18 |
"invalid_format": _("Input must be a JSON dictionary."), |
| 19 |
} |
| 20 |
|
| 21 |
def prepare_value(self, value): |
| 22 |
if isinstance(value, dict): |
| 23 |
return json.dumps(value, ensure_ascii=False) |
| 24 |
return value |
| 25 |
|
| 26 |
def to_python(self, value): |
| 27 |
if not value: |
| 28 |
return {} |
| 29 |
if not isinstance(value, dict): |
| 30 |
try: |
| 31 |
value = json.loads(value) |
| 32 |
except json.JSONDecodeError: |
| 33 |
raise ValidationError( |
| 34 |
self.error_messages["invalid_json"], |
| 35 |
code="invalid_json", |
| 36 |
) |
| 37 |
|
| 38 |
if not isinstance(value, dict): |
| 39 |
raise ValidationError( |
| 40 |
self.error_messages["invalid_format"], |
| 41 |
code="invalid_format", |
| 42 |
) |
| 43 |
|
| 44 |
# Cast everything to strings for ease. |
| 45 |
for key, val in value.items(): |
| 46 |
if val is not None: |
| 47 |
val = str(val) |
| 48 |
value[key] = val |
| 49 |
return value |
| 50 |
|
| 51 |
def has_changed(self, initial, data): |
| 52 |
""" |
| 53 |
Return True if data differs from initial. |
| 54 |
""" |
| 55 |
# For purposes of seeing whether something has changed, None is |
| 56 |
# the same as an empty dict, if the data or initial value we get |
| 57 |
# is None, replace it w/ {}. |
| 58 |
initial_value = self.to_python(initial) |
| 59 |
return super().has_changed(initial_value, data) |