首页 > 解决方案 > 如何在 django 的媒体文件夹中创建和保存 csv 文件?

问题描述

我在 django 中使用 HttpResponse 创建一个 csv 文件,我还想将它保存在媒体文件夹中。我在 settings.py 中设置了 MEDIA_ROOT

def to_csv(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=industry.csv'
    writer = csv.writer(response)
    data = Industry.objects.all()
    writer.writerow(['Name','Workplace and Designation','Contact No.','Email ID','Purpose of Visit','Self Employed Details'])
    for row in data:
        writer.writerow([row.name, row.wp_des, row.mobileno, row.email, row.purpose, row.semp_details])
    
    return response

它创建并下载 csv 文件,但我也想将它保存在媒体文件夹中

标签: pythondjango

解决方案


使用settings

from django.conf import settings

writer = csv.writer(settings.MEDIA_ROOT / file)

推荐阅读