[英]How to get data from form and show in dropdown in django
What I m trying to do:我正在尝试做的事情:
Upload a CSV file(Form #1) and show header of a CSV file in the dropdown (Form #2).上传 CSV 文件(表格 #1)并在下拉列表(表格 #2)中显示 CSV 文件的 header。 and these forms are on the same page.这些 forms 在同一页上。
What I have tried:我试过的:
for now I able to upload CSV file and display header in a webpage.现在我可以上传 CSV 文件并在网页中显示 header 。
index.html索引.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视图.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)
You can use AJAX request to handle this.您可以使用 AJAX 请求来处理此问题。 You can check this answer , which has a sample AJAX request.您可以查看这个答案,其中有一个示例 AJAX 请求。 In the views.py
file, you can handle the request by checking request.is_ajax()
and return the context you produce from CSV file via JsonResponse
.在views.py
文件中,您可以通过检查request.is_ajax()
来处理请求,并通过JsonResponse
返回您从 CSV 文件中生成的上下文。 At the success part of the AJAX call, you can manipulate the dropdown DOM element.在 AJAX 调用的成功部分,您可以操作下拉 DOM 元素。 There is a good tutorial here . 这里有一个很好的教程。 If you are not familiar with these, feel free to ask about the parts you are confused.如果您不熟悉这些,请随时询问您感到困惑的部分。
So data was in a list I just have to loop through <option>
:所以数据在一个列表中,我只需要遍历<option>
:
<select class="custom-select" id="inputGroupSelect01">
{% for x in loaded_data %}
<option value="{{ x }}">
{{ x }}
</option>
{% endfor %}
</select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.