0

I am working on creating a widget so clients can easily modify model's Json field in django admin.

Env Info: django-version: 3.1.14

Before drive into the widget, this is a simplify version of my model:

class Property(PolymorphicModel):
    """Basic information about property"""
    ...
    address = models.JSONField(blank=True, null=True, default=dict,)
    ...

And this how I am declaring the form:

class PropertyForm(forms.ModelForm):
    class Meta:
        model = Property
        fields = [
            "address",
          ]
        widgets = {
            'address': JSONEditorWidget(),
        }

I've already manage to convert json file into django admin inputs by using the following code:

class JSONEditorWidget(forms.widgets.Input):
    def as_field(self, name, key, value):
        """ Render key, value as field """
        new_name = name + '__' + key
        self.attrs = self.build_attrs({new_name:key})
        self.attrs['value'] = utils.encoding.force_text(value)
        return u'%s: <input%s />' % (new_name, forms.utils.flatatt(self.attrs))

    def to_fields(self, name, json_obj):
        """Get list of rendered fields for json object"""
        inputs = []
        for key, value in json_obj.items():
            inputs.append(self.as_field(name, key, value))
        return inputs

    def value_from_datadict(self, data, files, name):
        """I've been trying to get new values in this function but nothing successful"""

        return json.dumps(prev_dict)


    def render(self, name, value, attrs=None, renderer = None):
        # TODO: handle empty value (render text field?)

        if value is None or value == '':
            value = '{}'

        json_obj = json.loads(value)
        inputs = self.to_fields(name, json_obj)

        # render json as well
        inputs.append(value)

        return utils.safestring.mark_safe(u"<br />".join(inputs))

with this I could go from this:

enter image description here

To this:
enter image description here

My problem now is to catch the new values when user clicks on save/save and continue, so I can convert them into json file to save new records on postgres.

Ive tried with the function value_fromdatadict() but couldn't manage a way to get new values in the input box...

If anyone can helps me I will be so glad, I've been dealing with this a while and this is driving me crazy

Dragonthoughts
  • 2,180
  • 8
  • 25
  • 28

0 Answers0