Home > Software engineering >  Django download return
Django download return

Time:11-09

simple question please, my POST in the views returns a json format dictionary

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']
                        }],
                        }
                    }
                }
            }

then I am returning the code formatted into json using:

            return JsonResponse(nested_data)

This shows me the json rendered in the browser, but how do I download this return? In my index.html the submit button is rendering the return from the view, but I need to submit the forms and to download the content into .json file, something needs to be put into the href?

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

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

CodePudding user response:

You should define a function to write the json in views.py or index.html.

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

if you gonna write it in views.py, you could write the bellow lines in the js code section.

csrfmiddlewaretoken: "{{ csrf_token }}"

CodePudding user response:

You need change the response content type to 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'
)
  • Related