如何使用文件内容返回HTTP响应并重新呈现页面

时间:2018-06-17 18:42:33

标签: django

我有一个简单的页面,其中一个视图显示一个表单。单击表单的“提交”后,将在浏览器中下载文件。以下是我的视图代码的样子(我已经删除了大部分不相关的代码,以帮助突出我想要问的内容):

from django.contrib import messages
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from django import forms

# My custom form
from .forms import CalendarForm

def get_name(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':

        # create a form instance and populate it with data from the request
        form = CalendarForm(request.POST)

        # check whether it's valid
        if form.is_valid():
            # Fetch the form data here, and generate test.pdf
            # file based on form data (code removed for brevity)

            # Build HTTP request containing contents of static file to download
            with open('test.pdf', 'rb') as fh:
                resp = HttpResponse(fh.read(), content_type="application/pdf")
                resp['Content-Disposition'] = ('attachment;filename=test.pdf')

            # Return HTML response containing file contents: I also
            # want to re-render the calendar.html page here but don't know how
            return resp
        else:
            # Do error stuff (code removed for brevity)

    # if a GET (or any other method) we'll create a blank form
    else:
        form = CalendarForm()

    # Re-render the page
    return render(request, 'calendar.html', {'form': form})

如果返回包含文件内容的响应,我还想重新加载calendar.html页面,就像get_name的最后一个return语句一样。我没有网络开发方面的经验,所以我确信这里有一种设计模式或者我缺少的东西。

在这里安排事情的正确方法是什么,以便提交正确的表单会导致文件被下载,正在重新加载calendar.html页面?

0 个答案:

没有答案