jmrivas86 / django-json-widget

An alternative widget that makes it easy to edit the new Django's field JSONField (PostgreSQL specific model fields)
MIT License
433 stars 88 forks source link

Unable to edit form field #40

Closed gh94uk closed 5 months ago

gh94uk commented 4 years ago

Description

I followed the instructions to get a basic example working. The field is editable in the admin interface but is not editable from within a ModelForm. A large textarea field is displayed in the HTML form but no data is shown or split.

What I Did

forms.py

class DataTestForm(ModelForm):
    class Meta:
        model = DataTest
        exclude = ["slug"]
        widgets = {"eeg": JSONEditorWidget}

models.py

def facilities_imaging():
    return {"nonessions": 0, "esthourspermonth": 0}

class DataTest(Model):
    eeg = JSONField(blank=True, null=True, default=facilities_imaging)    # also tried without a default

form.html

# tried all separately
{{ form.eeg|as_crispy_field }}
{{ form.as_p }}

page source (eeg form field)

    <div id="div_id_eeg" class="form-group">

            <label for="id_eeg" class="">
                Eeg
            </label>
                <div class="">
                    <div style="height:500px;width:90%;display:inline-block;" class="jsoneditorwidget form-control" id="id_eeg"></div>
​
<textarea id="id_eeg_textarea" name="eeg" required="" style="display: none">{&quot;nonessions&quot;: 0, &quot;esthourspermonth&quot;: 0}</textarea>    # removing style shows the raw json
​
<script>
    (function() {
        var container = document.getElementById("id_eeg");
        var textarea = document.getElementById("id_eeg_textarea");
​
        var options = {"modes": ["text", "code", "tree", "form", "view"], "mode": "code", "search": true};    # tried changing modes
        options.onChange = function () {
            var json = editor.get();
            textarea.value=JSON.stringify(json);
        }
​
        var editor = new JSONEditor(container, options);
        var json = {"nonessions": 0, "esthourspermonth": 0};
        editor.set(json);
    })();
</script><input type="hidden" name="initial-eeg" value="{&quot;nonessions&quot;: 0, &quot;esthourspermonth&quot;: 0}" id="initial-id_eeg">
                </div>
    </div>
jmrivas86 commented 5 months ago

This widget is only for the admin, for now.