使用Django上传,处理和下载

时间:2019-03-10 03:11:20

标签: python django pandas

我是使用Django的新手,我打算用它上传文件,然后在处理后输出结果。

  • 在我的views.py文件中,它告诉我返回要转换为.csv的数据帧时存在问题。

  • 当尝试从html上传文件时,它会将我重定向到此:error. 403 Forbidden: CSRF verification failed. Request aborted

views.py:

from django.shortcuts import render
from .config import UPLOAD_DIR 
import os
import pandas as pd


#File extension checker
def read_data(data_input, **kwargs):

    #dictionary of file formats
    read_map = {"xls": pd.read_excel, "xlsm": pd.read_excel, "xlsx": pd.read_excel,
                "csv": pd.read_csv}

    #getting the file extension
    extension = os.path.splitext(data_input)[1].lower()[1:]

    #check if file extension and document upload validation
    assert extension in read_map
    assert os.path.isfile(data_input)


def upload(request):

    if request.method == "POST" and request.FILES["data_file"]:

        if "data_file" not in request.FILES:
            return render(request, 'qwe/form.html')


        data = request.FILES["data_file"]

        if data == "":
            return render(request, 'qwe/form.html')

        #uploads the data in the specific directory
        os.path.join(UPLOAD_DIR, data)

        # TO-DO DATA PROCESSING HERE

        #Error: Assigning to function call which doesn't return
        df = read_data(data)

        return df.to_csv("asd.csv")

    else:

        return render(request, 'qwe/form.html')

form.html:

<!DOCTYPE html>
<html>
<body>
<h1>Place holder</h1>

<h4>
    Please upload your training data here.
</h4>

<h5>
    Note: Please wait for the algorithm to finish then a download should commence.
    If there is no downloaded CSV, refresh this page and try again.
</h5>

<form method="post" enctype="multipart/form-data">
    <input type="file" name="data_file"/>
    <input type="submit" value="upload"/>
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您需要在表单中添加{% csrf_token %}

<form method="post" enctype="multipart/form-data">
  {% csrf_token %}
  <input type="file" name="data_file"/>
  <input type="submit" value="upload"/>
</form>