Загружать, обрабатывать и скачивать с помощью Django

#python #django #pandas

#python #django #панды

Вопрос:

Я новичок в использовании 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:

Вам нужно добавить {% csrf_token %} в свою форму:

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