我正在上传CSV文件,并希望将其加载到熊猫数据框中。将文件加载到视图中时出现问题。警告消息将发送到模板,表示该文件未发送到视图。
这是我的观点:
def showReadUploadedView(request, **kwargs):
context = {}
test_file = request.GET.get(u'testFile')
df = pd.read_csv(test_file)
context = {'df': df}
if not test_file:
messages.warning(request, f'No file to process! Please upload a file to process.')
return render(request, 'tasks/up_load.html', context)
这是我的模板:
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" class="form-control-file mt-1 mb-1" id="testFile">
<button class="btn btn-danger btn-sm mb-3 mt-1" type="submit">Process this</button>
<a href="{% url 'upload-task' task.id %}" class="btn btn-danger btn-sm mb-3 mt-1">Process Data</
</form>
答案 0 :(得分:0)
由于数据是通过POST方法发送的(如您在表单上定义的),因此request.GET
中将没有任何内容。但是,由于它是文件输入,因此也不会在request.POST
中。 Django专门处理文件并将其放入request.FILES
。
def showReadUploadedView(request, **kwargs):
context = {}
if request.method == 'POST':
test_file = request.FILES.get(u'testFile')
if test_file:
df = pd.read_csv(test_file)
context['df'] = df
else:
messages.warning(request, f'No file to process! Please upload a file to process.')
return render(request, 'tasks/up_load.html', context)
https://docs.djangoproject.com/en/2.2/topics/http/file-uploads/