简体   繁体   中英

Downloading files from a website on django

I have a website on a debian server. I fill out the template in docx format and save it. How do I download it to the user's devices?

 post_data = json.loads(request.body)
    date = post_data.get('date', False)
    price = post_data.get('price', False)
    pricesum = post_data.get('pricesum', False)
    startdate = post_data.get('startdate', False)
    enddate = post_data.get('enddate', False)


    doc = DocxTemplate('template.docx')

    dates = date
    prices = price

    tbl_contents = [{'expirationdate': expirationdate, 'price': price}
                    for expirationdate, price in zip(dates, prices)]

    context = {
        'tbl_contents': tbl_contents,
        'finalprice': sum(prices),
        'startdate': startdate,
        'enddate': enddate
    }

    doc.render(context)
    doc.save("static.docx")

I faced the same issue and I fixed it with this method.
My answer is inspired by this thread I hope it helps.

def fun(request):
    ...
    response = HttpResponse(content_type='application/vnd.openxmlformats- 
    officedocument.wordprocessingml.document')
    response['Content-Disposition'] = 'attachment; filename=file.docx'
    doc.save(response)
    return response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM