【问题标题】:How to read a file from Django MEDIA_ROOT and let the user download it in the front-end?如何从 Django MEDIA_ROOT 读取文件并让用户在前端下载?
【发布时间】:2021-04-20 07:09:45
【问题描述】:

我的看法如下:

def import_data(request):
    if request.method == "GET::
        column_names = network_asset._meta.fields #network_asset is the Model name
        column_names = [x.name for x in column_names]
        with open(os.path.join(MEDIA_ROOT, 'excel_templates', 'template.csv'), 'w+', newline = '') as file:
            writer = csv.writer(file)
            writer.writerow(column_names)

现在,我想将文件作为上下文传递给 HTML 页面并使用 <a> 标记下载它。

<a href="{{ myfile }}" download > Download {{ myfile }}</a>

我的 settings.py 有

# Media files (Excel templates, downloadable files)

MEDIA_ROOT = os.path.join(BASE_DIR,'media/')
MEDIA_URL  = '/media/'

Urls.py 有

urlpatterns = [
    re_path('^network/',include('network.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 


提前致谢

【问题讨论】:

    标签: html django django-models django-views


    【解决方案1】:

    我通过纯粹的运气和试错法找到了答案。 我需要将url 传递给上下文。需要将其放在其中一个视图中

        file_path = os.path.join(MEDIA_ROOT, 'excel_templates')
        file_name = 'template.csv'
        myfiles = [f for f in os.listdir(file_path)]
        context = {}
        context['myfiles'] = myfiles
        file_name = context.get('myfiles')[0]
            
        myfile_url = os.path.join(MEDIA_URL,'excel_templates', file_name)
            
        return render(request,'network/import_data.html', context = {
                'myfile_url':myfile_url
        })    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-13
      • 2021-04-12
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 1970-01-01
      相关资源
      最近更新 更多