2👍
✅
The issue you’re having is that Django uses it’s JSONField
form field to try and deserialize the object in the admin – this fails because it just uses json.dumps()
which cannot handle your PostalAddress
object.
You have overridden the model field, but you will also need to override the form field used in the admin. The documentation describes how to specify a custom form field for a model field.
Something like this:
from django.contrib.postgres.forms import JSONField
# Define a new form field
class PostalAddressJSONField(JSONField):
def prepare_value(self, value):
# Here, deserialize the object in a way that works.
# I've copied what you've done in your model field.
return json.dumps(value.__dict__)
Then specify this new form field in your PostalAddressField
:
class PostalAddressField(JSONField):
def formfield(self, **kwargs):
defaults = {'form_class': PostalAddressJSONField}
defaults.update(kwargs)
return super().formfield(**defaults)
The ModelAdmin
form should now use this custom form field, and be able to deserialize it correctly.
Source:stackexchange.com