Skip to main content
 首页 » 编程设计

python之使用 Django 上传、处理和下载

2024年11月24日24shihaiming

我刚开始使用 Django,我打算用它来上传文件,然后在处理后输出结果。

  • 在我的 views.py 文件中,它告诉我返回数据框时出现问题,我正尝试将其转换为 .csv。

  • 尝试从 html 上传文件时,它会将我重定向到此:错误。 403 Forbidden:CSRF 验证失败。请求中止。

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') 

表单.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> 

请您参考如下方法:

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

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