簡體   English   中英

使用自定義小部件覆蓋 django JSONField

[英]Use custom widget to override django JSONField

我正在嘗試使用像 django-json-widget 這樣的 3 方小部件來編輯表單中的 JSONField。

這是我的表單到目前為止的樣子:

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

這段代碼運行良好,但界面相當難看。 我正在尋找django-json-widget package 之類的東西,以便能夠編輯 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(widget=JSONEditorWidget(mode='code'))
<div class="container">
  {{ Form.media }}
  
  <form action="" method="post">
    {% csrf_token %} {{ Form.as_p}}
    <input type="submit" value="Submit" />
  </form>
</div></code></pre>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM