2015-05-31 05:13:58 +08:00
|
|
|
import json
|
|
|
|
|
|
|
|
from django import forms
|
2016-03-27 03:11:57 +08:00
|
|
|
from django.utils import six
|
2015-05-31 05:13:58 +08:00
|
|
|
from django.utils.translation import ugettext_lazy as _
|
|
|
|
|
|
|
|
__all__ = ['JSONField']
|
|
|
|
|
|
|
|
|
2016-03-27 03:11:57 +08:00
|
|
|
class InvalidJSONInput(six.text_type):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2015-05-31 05:13:58 +08:00
|
|
|
class JSONField(forms.CharField):
|
|
|
|
default_error_messages = {
|
|
|
|
'invalid': _("'%(value)s' value must be valid JSON."),
|
|
|
|
}
|
2016-06-13 20:09:54 +08:00
|
|
|
widget = forms.Textarea
|
2015-05-31 05:13:58 +08:00
|
|
|
|
|
|
|
def to_python(self, value):
|
2016-07-26 20:18:08 +08:00
|
|
|
if self.disabled:
|
|
|
|
return value
|
2015-05-31 05:13:58 +08:00
|
|
|
if value in self.empty_values:
|
|
|
|
return None
|
|
|
|
try:
|
|
|
|
return json.loads(value)
|
|
|
|
except ValueError:
|
|
|
|
raise forms.ValidationError(
|
|
|
|
self.error_messages['invalid'],
|
|
|
|
code='invalid',
|
|
|
|
params={'value': value},
|
|
|
|
)
|
|
|
|
|
2016-03-27 03:11:57 +08:00
|
|
|
def bound_data(self, data, initial):
|
|
|
|
if self.disabled:
|
|
|
|
return initial
|
|
|
|
try:
|
|
|
|
return json.loads(data)
|
|
|
|
except ValueError:
|
|
|
|
return InvalidJSONInput(data)
|
|
|
|
|
2015-05-31 05:13:58 +08:00
|
|
|
def prepare_value(self, value):
|
2016-03-27 03:11:57 +08:00
|
|
|
if isinstance(value, InvalidJSONInput):
|
|
|
|
return value
|
2015-05-31 05:13:58 +08:00
|
|
|
return json.dumps(value)
|