Kode sumber untuk django.contrib.postgres.forms.hstore

[docs]classHStoreField(forms.CharField):""" A field for HStore data which accepts dictionary JSON input. """widget=forms.Textareadefault_error_messages={'invalid_json':_('Could not load JSON data.'),'invalid_format':_('Input must be a JSON dictionary.'),}defprepare_value(self,value):ifisinstance(value,dict):returnjson.dumps(value)returnvaluedefto_python(self,value):ifnotvalue:return{}ifnotisinstance(value,dict):try:value=json.loads(value)exceptValueError:raiseValidationError(self.error_messages['invalid_json'],code='invalid_json',)ifnotisinstance(value,dict):raiseValidationError(self.error_messages['invalid_format'],code='invalid_format',)# Cast everything to strings for ease.forkey,valinvalue.items():ifvalisnotNone:val=str(val)value[key]=valreturnvaluedefhas_changed(self,initial,data):""" Return True if data differs from initial. """# For purposes of seeing whether something has changed, None is# the same as an empty dict, if the data or initial value we get# is None, replace it w/ {}.initial_value=self.to_python(initial)