首页 > 解决方案 > 如何从模式创建动态表单字段

问题描述

我正在尝试制作一个基于用户选择的模式动态创建的 JSON Creator 表单。我举了一个例子,说明我希望一个人或多或少看起来像。

采用这个给定的模式:

{
    "type":"object"
    "properties":
        "color": {
            "type": "string",
            "enum": ["red","green","blue"]
        },
        "unique_id": {
            "type": "string"
            "maxLength": 15 
        },
        "workload":{
            "type": "object",
            "properties":{
                "write_pre":{
                    "type": "number",
                    "minimum": -1
                },
                "read_pre":{
                    "type": "number",
                    "minimum": -1
                },
                "required": ["write_pre","read_pre"],
                "additionalProperties": false
            }
        },
        "required": ["color", "unique_id"],
        "additionalProperties": false
}

我希望我的表单看起来像这样:

{% load static %}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <link rel="stylesheet" href="{% static "css/background.css" %}">
    </head>
    <body>
      <div class="navbar">
      </div>
        <h1>Welcome To The JSONCreator</h1>
        <form method="post" class="creator">
          {% csrf_token %}
          <h4>color: *required</h4>
                <select name="color" required>
                  <option value="red">red</option>
                  <option value="green">green</option>
                  <option value="blue">blue</option>
                </select>
          <h4>unique_id: *required</h4>
            <input type="text" name="unique_id" required>
          <h4>workload:</h4>
            <h5>work_pre: *required</h5>
              <input type="number" min="-1" name="workloadWork_pre" required>
            <h5>read_pre: *required</h5>
              <input type="number" min="-1" name="workloadRead_pre" required>
          <br><br><input type="submit" value="submit">
        </form>
    </body>
</html>

我的问题是我不知道如何将表单字段自动更新为架构中给定的属性字段。我打算不使用 Django 的表单而不是 HTML 来编写表单。我只是在这个例子中使用 HTML 作为一个非常快速的模型,以便为我的问题提供更多上下文。

我正在使用 Python2.7 和 Django 1.11 并且没有数据库

标签: pythonjsondjangoformsdynamic

解决方案


推荐阅读