【问题标题】:Django download returnDjango下载返回
【发布时间】:2021-12-21 14:25:06
【问题描述】:

简单的问题,我在视图中的 POST 返回一个 json 格式的字典

nested_data = {
            'name': cleaned_data3['theme_name'],
            'visualStyles': {
                'barChart': {
                    '*': {
                        'general': [{
                            'responsive': cleaned_data2['responsive'],
                            'keepLayerOrder': cleaned_data2['maintain_layer_order']
                        }],
                        'legend': [{
                            'show': cleaned_data['show'],
                            'position': cleaned_data['position'],
                            'showTitle': cleaned_data['show_title'],
                            'labelColor': {
                                'solid': {
                                    'color': '#666666'
                                }
                            },
                            'fontFamily': cleaned_data['font'],
                            'fontSize': cleaned_data['font_size']
                        }],
                        }
                    }
                }
            }

然后我将使用以下格式返回格式化为 json 的代码:

            return JsonResponse(nested_data)

这显示了在浏览器中呈现的 json,但是我如何下载这个返回值?在我的 index.html 中,提交按钮正在呈现视图的返回,但我需要提交表单并将内容下载到 .json 文件中,需要在 href 中放入一些东西吗?

  <input type="submit" value="Submit">

  <a href="{{ xxx }}" download>DOWNLOAD</a>

【问题讨论】:

    标签: json django


    【解决方案1】:

    你应该定义一个函数来在views.py或index.html中写入json。

    with open(file_name, "wb") as f:
            f.write(data)
    

    如果你要写在views.py中,你可以在js代码部分写下面几行。

    csrfmiddlewaretoken: "{{ csrf_token }}"
    

    【讨论】:

      【解决方案2】:

      您需要将响应内容类型更改为application/force-download

      response = JsonResponse(nested_data)
      response['Content-Type'] = 'application/force-download'
      return response
      
      
      # or ...
      
      return HttpResponse(
          simplejson.dumps(nested_data), 
          content_type='application/force-download'
      )
      

      【讨论】:

      • 嗨,这正是我要找的,谢谢 :)
      • 顺便说一句,我在没有强制下载的情况下用谷歌搜索了第二个解决方案
      • response = JsonResponse(nested_data) response['Content-Disposition'] = 'attachment; filename=my_theme.json' 返回响应
      • 是@mrl, ['Content-Disposition'] = '附件; ..' 是另一个不错的选择。允许您指定文件的名称。如果不是,则导航器使用 URL 中的名称。
      猜你喜欢
      • 2011-07-17
      • 1970-01-01
      • 1970-01-01
      • 2019-09-12
      • 1970-01-01
      • 1970-01-01
      • 2020-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多