使用自定义小部件覆盖 django JSONField

Use custom widget to override django JSONField

我正在尝试使用像 django-json-widget 这样的 3 方小部件来编辑我表单中的 JSON 字段。

到目前为止,我的表单是这样的:

class ConfigsForm(forms.Form):
    ks_config = JSONField()

这段代码工作正常,但界面很丑。我正在寻找类似 django-json-widget 包的东西,以便能够编辑 JSON 数据。但到目前为止,我无法正确实施它。 这是我的看法:

def configs_details(request, sim_id):
    simulation = get_object_or_404(Simulation, pk=sim_id)
    
    ks_config = os.path.join(os.getcwd(),'configs', str(simulation.uuid), 'ks_config.json')
    with open(ks_config) as jsn:

        form = ConfigsForm(request.POST or None,initial={'ks_config': json.load(jsn)})
        if form.is_valid():
            # validate and save
            pass

    template = 'sim_configuration.html'
    context = {'Form': form}
    return render(request,template, context)

我试过的.

在上面的表格中添加以下行:

class ConfigsForm(forms.Form):
    ks_config = JSONField()
    widgets = {
        'ks_config':  JSONEditorWidget(mode='code')
    }

此外,我必须专门使用 Form 而不是 ModelForm。

这是我的 HTML 表单页面:

{% extends 'base.html' %} {% block head %}
<title>Configs</title> {% endblock head %} {% block body %}
<div class="container">
  <br>
  <form action="" method="post">
    {% csrf_token %} {{ Form.as_p}}
    <input type="submit" value="Submit" />
  </form>
</div>
{% endblock body %}

在您的表单元素之上添加 {{ Form.media }}

class ConfigsForm(forms.Form):
    ks_config = JSONField(<b>widget=JSONEditorWidget(mode='code')</b>)
<div class="container">
  {{ Form.media }}
  
  <form action="" method="post">
    {% csrf_token %} {{ Form.as_p}}
    <input type="submit" value="Submit" />
  </form>
</div></code></pre>