How to write a dynamic file in django?

0

I want to write a dynamic file that generated me a report in txt format, for this I created a function that returns the file and downloads it, but it is returning empty. Here part of the code:

file_content = "Este es el contenido de los reportes"
file_name = "Report " + str(date.today()) + ".txt"
    file = open(file_name,'w')
    file.write(file_content")
    file.close()
    response = HttpResponse(content_type='application/force-download')
    response['Content-Disposition'] = 'attachment; filename={}'.format(file_name)
    response['X-Sendfile'] = file
    return response

At the end of this function if the file is returned to me, but it is empty .... jelpmi

    
asked by Jonnathan Carrasco 05.11.2018 в 17:55
source

1 answer

0

Greetings I will leave you a small guide that I use: first I get the current date and convert it to str:

import time
timestr = time.strftime("%Y%m%d-%H%M%S")
#output
20181105-123059

Well now we will create the file something like this:

file = open(timestr,'w') 

to write in the something like this:

    content="hola mundo"
    file.write(content) 

after writing, I proceed to record the data:

file.close() 

the result would have something like this:

I hope I will help you .. !!

    
answered by 05.11.2018 в 18:37