django-jsonform icon indicating copy to clipboard operation
django-jsonform copied to clipboard

Support for "additionalProperties" in string with choices

Open rptmat57 opened this issue 7 months ago • 3 comments

Hi, I was wondering if there was a way to have additional properties or a custom input option for the string type with choices. This would be useful when we want to offer a list of options but also let the user enter their own (without using a separate field)

Technically speaking, I believe this could be done by using the HTML input datalist attribute? https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/datalist

here is a Widget implementation I've used in the past:

class DatalistWidget(forms.TextInput):
    def __init__(self, attrs=None):
        if attrs is not None:
            attrs = attrs.copy()
            self.choices = attrs.pop("choices", [])
        super().__init__(attrs)

    def render(self, name, value, attrs=None, renderer=None):
        if attrs is None:
            attrs = {}
        attrs["list"] = f"{name}_datalist"
        options = self.choices
        datalist = f'<datalist id="{name}_datalist">'
        for option_value, option_label in options:
            datalist += f'<option value="{option_value}">{option_label}</option>'
        datalist += "</datalist>"
        return super().render(name, value, attrs, renderer) + datalist

rptmat57 avatar May 13 '25 15:05 rptmat57

It should be possible with oneOf. However, there's a bug (#181) right now which prevents it from working.

This should work (but doesn't yet):

"additionalProperties": {
  "oneOf": [
    {
      "type": "string",
      "enum": ["a", "b", "c"]
    },

    {
      "type": "string"
    }
  ]
}

I'll see if it can be fixed by this weekend.
Thanks for opening the issue.

bhch avatar May 14 '25 03:05 bhch

Oh that makes sense, didn't think about using oneOf. I am pretty new to this JsonSchema stuff, but your library is really awesome!! I was looking specifically for this type of package and I am glad I found yours, it does everything I could think of, and more! It's a game changer.

Kudos to you!

rptmat57 avatar May 14 '25 19:05 rptmat57

@bhch any news on the bug fix #181? It would be awesome if that could be fixed!

rptmat57 avatar Jun 22 '25 21:06 rptmat57