django项目中如何连接js和python

问题描述 投票:0回答:1

我想从用户那里接收带有html页面的Excel,并使用js中的ajaxc算法将其传输到Python 所以它应该存储在特定的文件夹中并由Excel使用Python库等进行处理 以租赁链接的形式给用户一个新的Excel下载链接

`从 django.http 导入 JsonResponse 从 django.views.decorators.csrf 导入 csrf_exempt 导入操作系统

@csrf_exempt def process_excel(请求): 如果 request.method == 'POST': excel_file = request.FILES.get('excelFile')

    if excel_file:
        # Define the path to save the uploaded excel file
        save_path = 'D:/updatepj/'
        file_path = os.path.join(save_path, excel_file.name)

        # Save the uploaded excel file
        with open(file_path, 'wb') as destination:
            for chunk in excel_file.chunks():
                destination.write(chunk)

        # Create a response message
        response_data = {'message': 'Excel file uploaded successfully.'}
        return JsonResponse(response_data)
    else:
        response_data = {'message': 'No file was uploaded.'}
        return JsonResponse(response_data, status=400)

response_data = {'message': 'Invalid request method.'}
return JsonResponse(response_data, status=405)

在此创建您的观点。

DashboardView 类(LoginRequiredMixin,TemplateView): 通过

dashboard_view = DashboardView.as_view(template_name="dashboards/index.html") dashboard_crm_view = DashboardView.as_view(template_name="dashboards/dashboard-crm.html") ` 视图.py

我收到错误:不允许方法:/process_excel

javascript python django excel ajax
1个回答
-1
投票
## backend.py

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import os
import requests
import openpyxl

@csrf_exempt
def process_excel(request):
  if request.method == 'POST':
    excel_file = request.FILES.get('excelFile')
    filename = os.path.basename(excel_file.name)
    filepath = os.path.join('uploads', filename)
    excel_file.save(filepath)

    # Process the Excel file using Python libraries
    workbook = openpyxl.load_workbook(filepath)
    sheet = workbook.active

    # Generate a new Excel file with the processed data
    new_filename = 'processed_' + filename
    new_filepath = os.path.join('uploads', new_filename)
    new_workbook = openpyxl.Workbook()
    new_sheet = new_workbook.active

    # Copy the data from the original Excel file to the new Excel file
    for row in range(1, sheet.max_row + 1):
        for col in range(1, sheet.max_column + 1):
            new_sheet.cell(row, col).value = sheet.cell(row, col).value

    new_workbook.save(new_filepath)

    # Generate a download link for the new Excel file
    url = '/uploads/' + new_filename
    return JsonResponse({'url': url})

// frontend.js
function processExcel() {
  var formData = new FormData();
  formData.append('excelFile', document.getElementById('excelFile').files[0]);

  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/process_excel');
  xhr.onload = function() {
    if (xhr.status == 200) {
      var data = JSON.parse(xhr.responseText);
      var url = data.url;
      var a = document.createElement('a');
      a.href = url;
      a.download = 'processed_excel.xlsx';
      a.click();
    } else {
      alert('Something went wrong!');
    }
  };
  xhr.send(formData);
}
© www.soinside.com 2019 - 2024. All rights reserved.