0

I need to get some data from my template and send it back to my Django function using ajax, create a docx file and download it

Django Function

def download_docx_file(request):
    if request.method == 'GET':
        language = request.GET['lang']
        data = request.GET['data']
        converter = {'data': 'This is the real data'}
        document = Document()
        document.add_heading(f'{language} -- {converter[data]}', 0)
        response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
        response['Content-Disposition'] = 'attachment; filename=download.docx'
        document.save(response)
        return response
    return HttpResponse("hello")

AJAX

$("#dwnBtn").click(function(){
$.ajax({
url : "docx/",
type:"GET",
data : { lang : 'lang', data:'data' },
success : function(data){
console.log(data)

}
})
});

I am getting sth like the below response from AJAX response:

Response console.log(data)

�ܝBp��݂�;|C�ھ�w������=O���]]�%�N�����#+�reup����������Y������̉�J����3)� O��C����F�M�P�&�����rA�@��7T.��z(%h��x�x0�0Z�-i��%q�e�M�����i�"�c��-/��j��齔/ļL瞄�0� �� >�o��[��6 멆�n��s�$� �#>˘ '��wT�� ���3�36DK�+�̓�t6 ��r��sA:���x�<>n������'U��RLqA+���ݺ�BM��:4ĞP�}���:�}ߣP����?F)�9-�W0���2�{x��#2v8N.$V�>X=/�+�c}���ּ�\y���*�J\�� ���90�T�L� 3p���*Sfj(���PWWz��O�s�9]&����iO|�9�;�5��ʘdW�cl% �%;����u���%[�5������Q]$��[L>���yXg�9��2+&,iFs�Q�����u�.�E(�>W��+��M ؟E������i|���k�k�c蟴CcG�j��4s|x �F1�}��Y��,29�0M=-O����m\L��y��^On^���\���u��a���F9:zc�Sy�-�g��fu�n�C�T:{ ��4&/ ��LM9�98� �&Pnc�!��m�r�~��)74�04��0�0������M�~"��.ikjG��M�

how can I save this binary data as a .docx file? Thank you in advance

Teq Teq
  • 36
  • 2
  • Does it have to be ajax? You can just do a `location = 'docx/?lang=lang&data=data';` – Musa Mar 19 '22 at 17:42
  • in fact, the value inside the data is more complicated than a simple string. That's why I don't use URLs. – Teq Teq Mar 19 '22 at 17:58
  • You can use `$.param` to convert your complicated data to a url param string. `location = 'docx/?'+$.param(complicated_data_object); – Musa Mar 19 '22 at 18:23
  • Thanks Musa I did it as you suggest window.location ="{% url 'my_url' 'lang' 'data' %}".replace(/data/, JSON.stringify(arr)); and it kinda solved my issue. However, I'm still wondering is it possible to convert that binary data? – Teq Teq Mar 19 '22 at 18:46
  • You can look at this answer to see how to get the data as a blob https://stackoverflow.com/questions/17657184/using-jquerys-ajax-method-to-retrieve-images-as-a-blob/17682424?r=SearchResults&s=3|2.3184#17682424 – Musa Mar 20 '22 at 00:02

0 Answers0