jazzband / django-smart-selects

chained and grouped selects for django forms
https://django-smart-selects.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
1.11k stars 348 forks source link

bindfields.js expects 'data-value' to be JSON but widgets.py doesn't always encode it #227

Open davmlaw opened 7 years ago

davmlaw commented 7 years ago

Checklist

Put an x in the bracket when you have completed each task, like this: [x]

Steps to reproduce

  1. Have a formset with 2 smart selects, load the page

Actual behavior

Uncaught SyntaxError: Unexpected token _ in JSON at position 2 at JSON.parse (<anonymous>) at initItem (bindfields.js:8) at HTMLSelectElement.<anonymous> (bindfields.js:25) at Function.each (jquery-2.2.4.js:365) at HTMLDocument.<anonymous> (bindfields.js:24) at fire (jquery-2.2.4.js:3187) at Object.fireWith [as resolveWith] (jquery-2.2.4.js:3317) at Function.ready (jquery-2.2.4.js:3536) at HTMLDocument.completed (jquery-2.2.4.js:3552)

Expected behavior

No Javascript error occurs.

Suggested Fix:

The problem is that in widgets.py, ChainedSelect.render line 138 sets:

attrs["data-value"] = "null" if value is None or value == "" else value

So when the string "foo" is decoded, it fails with JSON decode error above (should be '"foo"' (with quotes))

I believe the fix should be:

attrs["data-value"] = "null" if value is None else json.dumps(value)

Which is the same as line 244 in ChainedSelectMultiple

manelclos commented 4 years ago

@davmlaw can you reproduce with latest master version?

davmlaw commented 4 years ago

Sorry, I use Django autocomplete light now, so can't easily test this. Feel free to close if you think it's fixed.