使用Django上传多个表单字段的多个文件?

时间:2017-08-01 16:41:39

标签: python django-models django-forms django-templates

我已经写下了一个视图和模板来上传两个带有两个不同表单字段的文件,但遗憾的是它只上传了一个来自第一个输入文件的文件。

这是模板文件,应将两个文件上传到媒体文件夹: tamplate.html

{% extends 'protocol/base.html' %}

{% load staticfiles %}


{% block content %}

<style type="text/css">

.button {
    background-color:  #ff9800; /* Green */
    border: none;
    color: black;
    padding: 10px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin-left: 250px;
    margin-top: 10px;
    margin-bottom: 30px;
}

.input {
    margin-left: 250px;
}
.text {
    margin-left: 250px;
}
.heading{
    margin-left: 250px;
}
</style>

 <form method="post" enctype="multipart/form-data">
 <div class="heading">
 <h1> Machine Learning Modeling.. </h1>
 <h2> Upload CSV files contains both, positive and Negative peptides.. </h2>
 </div>
    {% csrf_token %}
    <input class="input" type="file" name="myfile">
    <input class="input" type="file" name="myfile_1">
    <button class="button" type="submit">Upload</button>
  </form>

  {% if uploaded_file_url %}
    <p class="text" >File uploaded successfully. </p>
  {% endif %}

{% endblock %}

Views.py

from django.shortcuts import render
from django.core.files.storage import FileSystemStorage
from django.shortcuts import render, redirect
from django.conf import settings

import os
import glob
from django.core.files.storage import FileSystemStorage
#from django.core.servers.basehttp import FileWrapper
from wsgiref.util import FileWrapper
import urllib, mimetypes
from django.http import HttpResponse
from django.utils.encoding import smart_str


# Create your views here.
def predict(request):



    if request.method == 'POST' and request.FILES['myfile']:
        myfile = request.FILES['myfile']
        fs = FileSystemStorage()
        filename = fs.save(myfile.name, myfile)
        uploaded_file_url = fs.url(filename)

    if request.method == 'POST' and request.FILES['myfile_1']:
        myfile = request.FILES['myfile_1']
        fs = FileSystemStorage()
        filename = fs.save(myfile.name, myfile)
        uploaded_file_url = fs.url(filename)


        return render(request, 'prediction/thanks.html', {})

    return render(request, 'prediction/prediction.html')

如何使用表单的多个输入字段上传多个文件

1 个答案:

答案 0 :(得分:0)

您可以尝试在.get上使用request.FILES方法。 在下面提供的代码中,我还重命名了您的myfile变量,因此它们是唯一的......这只是一种很好的做法。

# Posted form.
if request.method == "POST":

    if request.FILES.get('myfile', None):
        file_1 = request.FILES.get('myfile')
        fs = FileSystemStorage()
        filename = fs.save(file_1.name, file_1)
        uploaded_file_url = fs.url(filename)

    if request.FILES.get('myfile_1', None):
        file_2 = request.FILES.get('myfile_1')
        fs = FileSystemStorage()
        filename = fs.save(file_2.name, file_2)
        uploaded_file_url = fs.url(filename)

尝试这个建议。如果它不起作用,请尝试打印表单提交中的输出,看看发生了什么。