文件下载功能在django views.py中不起作用

发布于 2025-01-25 02:05:52 字数 2826 浏览 2 评论 0原文

[supporting.html]

<a href="/supporting/download/"><button type="button">Download File</button></a>

[supporting/urls.py]

from django.urls import path
from . import views

urlpatterns =[
    path('supporting/download/',views.download),
    ...
    ]

[supporting/views.py]

def download(request):
    output = io.BytesIO()
    workbook = xlsxwriter.Workbook(output)
    worksheet = workbook.add_worksheet()
    merge_format = workbook.add_format({'align': 'center', 'valign': 'vcenter'})

    supportings = Supporting.objects.filter(is_deleted='0') \
        .annotate(date_str=Cast(TruncDate('in_date'), CharField())) \
        .values_list('date_str', 'date_str', 'study_name',
                 'register_number', 'person_name', 'person__no', 'date_str', 'kinds', 'teacher', 'comment', 'technician')

supportings = pd.DataFrame.from_records(supportings)
supportings = supportings.rename(columns={0: 'Days',
                                          1: 'Date',
                                          2: 'Study name',
                                          3: 'Register Number',
                                          4: 'Name',
                                          5: 'No',
                                          6: 'Time',
                                          7: 'Kinds',
                                          8: 'Teacher',
                                          9: 'Comment',
                                          10: 'Technician'})

for supporting in supportings['Days'].unique():
    # find indices and add one to account for header
    u = supportings.loc[supportings['Days'] == supporting].index.values + 1

    if len(u) < 2:
        pass  # do not merge cells if there is only one supporting Days
    else:
        # merge cells using the first and last indices
        worksheet.merge_range(u[0], 0, u[-1], 0, supportings.loc[u[0], 'Days'], merge_format)


workbook.close()
output.seek(0)

supportings.set_index(supportings.columns[:-1].tolist()).to_excel('success.xlsx')

以上代码在jupyter笔记本中正常工作,并下载了文件。但是,当我在django中运行上述代码时,没有返回值,因此“ view supporting.views.downloaddid不返回httpresponse对象。它又不返回。”发生错误。

因此,我删除了to_excel方法,并添加了以下代码。但是,该文件无法下载。没有事件发生..

supportings.set_index(supportings.columns[:-1].tolist())

filename = 'Supporting_List.xlsx'
try:
    filename.encode('ascii')
    file_expr = 'filename="{}"'.format(filename)
except UnicodeEncodeError:
    file_expr = "filename*=utf-8''{}".format(quote(filename))

response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; ' + file_expr

return response

如果有人知道解决方案,请提供帮助。

[supporting.html]

<a href="/supporting/download/"><button type="button">Download File</button></a>

[supporting/urls.py]

from django.urls import path
from . import views

urlpatterns =[
    path('supporting/download/',views.download),
    ...
    ]

[supporting/views.py]

def download(request):
    output = io.BytesIO()
    workbook = xlsxwriter.Workbook(output)
    worksheet = workbook.add_worksheet()
    merge_format = workbook.add_format({'align': 'center', 'valign': 'vcenter'})

    supportings = Supporting.objects.filter(is_deleted='0') \
        .annotate(date_str=Cast(TruncDate('in_date'), CharField())) \
        .values_list('date_str', 'date_str', 'study_name',
                 'register_number', 'person_name', 'person__no', 'date_str', 'kinds', 'teacher', 'comment', 'technician')

supportings = pd.DataFrame.from_records(supportings)
supportings = supportings.rename(columns={0: 'Days',
                                          1: 'Date',
                                          2: 'Study name',
                                          3: 'Register Number',
                                          4: 'Name',
                                          5: 'No',
                                          6: 'Time',
                                          7: 'Kinds',
                                          8: 'Teacher',
                                          9: 'Comment',
                                          10: 'Technician'})

for supporting in supportings['Days'].unique():
    # find indices and add one to account for header
    u = supportings.loc[supportings['Days'] == supporting].index.values + 1

    if len(u) < 2:
        pass  # do not merge cells if there is only one supporting Days
    else:
        # merge cells using the first and last indices
        worksheet.merge_range(u[0], 0, u[-1], 0, supportings.loc[u[0], 'Days'], merge_format)


workbook.close()
output.seek(0)

supportings.set_index(supportings.columns[:-1].tolist()).to_excel('success.xlsx')

The above code works normally in Jupyter notebook and the file is downloaded. However, when I run the above code in Django, there is no return value, so "The view supporting.views.downloaddidn't return an HttpResponse object. It returned None instead." An error occurs.

So, I deleted the to_excel method and added the code as below. However, the file cannot be downloaded. No event occurs..

supportings.set_index(supportings.columns[:-1].tolist())

filename = 'Supporting_List.xlsx'
try:
    filename.encode('ascii')
    file_expr = 'filename="{}"'.format(filename)
except UnicodeEncodeError:
    file_expr = "filename*=utf-8''{}".format(quote(filename))

response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; ' + file_expr

return response

If anyone knows a solution, please help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文