【问题标题】:How to get data from form and show in dropdown in django如何从表单中获取数据并在 django 的下拉列表中显示
【发布时间】:2020-09-04 23:32:53
【问题描述】:

我想做的事:

上传 CSV 文件(表格 #1)并在下拉列表中显示 CSV 文件的标题(表格 #2)。 并且这些表单在同一页上。

我尝试过的:

现在我可以上传 CSV 文件并在网页中显示标题。

index.html

<form action="" method="POST" enctype="multipart/form-data">
                {% csrf_token %}
                <div class="form-group">
                    <label for="file1">Upload Files</label>
                    <div class="custom-file">
                    <input type="file" accept=".csv" id="file1" name="file"  required="True" class="form-control custom-file-input">
                    <label class="custom-file-label" for="file1"></label>
                    </div>
                </div>
                <div class="form-group d-flex justify-content-center">
                    <button type="submit" class="btn text-white w-50" value="Upload">Upload</button>
                </div>
            </form>

views.py

def read_csv(request):
    csv_file = request.FILES['file']
    data = pd.read_csv(csv_file)
    i = list(data.head(0))
    context = {'loaded_data': i}
    return render(request, "WebApp/index.html", context)

【问题讨论】:

    标签: python django django-rest-framework django-forms django-views


    【解决方案1】:

    您可以使用 AJAX 请求来处理这个问题。你可以查看这个answer,它有一个示例 AJAX 请求。在views.py 文件中,您可以通过检查request.is_ajax() 来处理请求,并通过JsonResponse 返回您从CSV 文件生成的上下文。在 AJAX 调用的成功部分,您可以操作下拉 DOM 元素。有一个很好的教程here。如果您不熟悉这些,请随时询问您感到困惑的部分。

    【讨论】:

    • 非常感谢。我已经调查过了,但答案很简单。
    【解决方案2】:

    所以数据在一个列表中,我只需要遍历&lt;option&gt;

    <select class="custom-select" id="inputGroupSelect01">
       {% for x in loaded_data %}
          <option value="{{ x }}">
                 {{ x }}
          </option>
       {% endfor %}
    </select>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-26
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 2020-01-22
      相关资源
      最近更新 更多