Изменить имя файла в Джанго Пиза

Я хотел сделать шаблон в PDF-файл. Итак, я посмотрел это и нашел следующий код:

def write_pdf(template_src, context_dict):
    template = get_template(template_src)
    context = Context(context_dict)
    html = template.render(context)
    result = StringIO.StringIO()
    pdf = pisa.pisaDocument(StringIO.StringIO(
        html.encode("UTF-8")), result, encoding='UTF-8')


    if not pdf.err:
        return http.HttpResponse(result.getvalue(),
                                 mimetype='application/pdf', )
    return http.HttpResponse('Gremlins ate your pdf! %s' % cgi.escape(html))

Это прекрасно работает, но я не могу изменить имя файла. Если я начну загрузку этого файла, firefox сообщит, что "1.pdf" загружен. Итак, вот мой вопрос: как я могу изменить имя файла шаблона? Я искал это, но я не нашел ответа.. (возможно, я просто слишком тупой ^^)

Большое спасибо за Вашу помощь

1 ответ

Решение

Ты очень близко Вам просто нужно установить Content-Disposition вашего ответа:

def write_pdf(template_src, context_dict):
    template = get_template(template_src)
    context = Context(context_dict)
    html = template.render(context)
    result = StringIO.StringIO()
    pdf = pisa.pisaDocument(StringIO.StringIO(
        html.encode("UTF-8")), result, encoding='UTF-8')

    if not pdf.err:
        response = http.HttpResponse(result.getvalue(),
                                 mimetype='application/pdf')

        response['Content-Disposition'] = 'attachment; filename=whatever.pdf'

        return response
    return http.HttpResponse('Gremlins ate your pdf! %s' % cgi.escape(html))
Другие вопросы по тегам