python - 项目中不同应用程序的 Django 文件上传?

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

我正在开发一个项目,其中有各种应用程序,例如协议(protocol)、预测等。

要执行一些计算“协议(protocol)”和“预测”应用程序需要用户以文件上传的形式输入。

我已经实现了以下模式,该模式将文件成功上传到基本项目目录中的“media”目录中。

我想以这种方式实现文件上传,以便它可以上传各个应用程序目录而不是公共(public)媒体目录的文件。

我的代码是这样的:

View .py

def simple_upload(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)
        print uploaded_file_url

        return render(request, 'protocol/submit_job.html', {})

    return render(request, 'protocol/main_protocol.html')

url.py

url(r'^protocol/$', views.simple_upload, name='simple_upload'),

html

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

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

这个模式对我有用,并将所有文件上传到媒体目录中。 我应该进行哪些更改才能以应用程序特定的方式上传文件。

例如:

prediction/Input/uploaded_file_1.csv
protocol/Input/uploaded_file_2.csv

我不想将任何文件保存或上传到模型或数据库中。 Appl 将在下一次用户输入之前删除上传的文件。

最佳答案

FileSystemStorage 类具有 location 参数,默认设置为 MEDIA_ROOT,但您可以将其更改为任何其他目录。

首先,更改类的默认位置:

fs = FileSystemStorage(location='prediction/Input/')

然后您可以按照与现在相同的方式保存文件。不要忘记写入权限。

以下是该类的文档: https://docs.djangoproject.com/en/2.0/ref/files/storage/#the-filesystemstorage-class

关于python - 项目中不同应用程序的 Django 文件上传?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48619044/

相关文章:

python - Django 可以在没有 FORMS 的情况下上传文件吗?

python - NumPy 是否具有均匀性函数?

django - django中是否有任何tile类型的概念

Django MPTT Postgres 更新查询运行缓慢

Django 按日期排序,但末尾有 "None"?

python - Sublime Text 删除 python 新属性自动完成

python - 在 Python 中用色标可视化位置的移动速度

python - Django CreateView 根据 url 参数自定义表单默认字段

Django 多对多调用太多

django - 跨 2 个 FK 到同一个表的相关对象的总和,有条件