Django:表单上的提交更新视图上的状态消息并下载文件

时间:2016-03-25 04:42:37

标签: python django django-forms django-templates

我的视图显示:状态消息,文本字段,提交按钮

选择提交可以成功或失败

对于成功的请求,我想下载一个文件并在视图上更新状态消息(" success")。如果失败,我想更新视图的状态消息("失败")。

def download_file(request):
    context = RequestContext(request)
    context['message'] = ''

    filename = request.POST.get('filename')
    data = get_file(filename)

    if data:
        response = HttpResponse(data, content_type="application/octet-stream")
        response['Content-Disposition'] = 'attachment; filename="download.bin"'
        return response   # NOT the desired behavior, this will only download the file, not update the view
    else:
        context['message'] = "failed"
        return render_to_response('download_page.html', context_instance=context)

download_page.html

<label>status: {{ message }}</label>
<form action="/download/" method="post"> 
    <label>filename: </label>
    <input id="filename" type="text" name="filename">
    <input type="submit" value="Submit">
</form>

1 个答案:

答案 0 :(得分:0)

Use django embed forms
在您的表单中,您只需要定义一个“clean_filename”函数,该函数会在找不到文件时引发错误。

您可以在模板中显示“消息”。

尝试:

{{ message }}
<form action="/download/" method="post">
    <label>filename: </label>
    <input id="filename" type="text" name="filename">
    <input type="submit" value="Submit">
</form>

我不推荐这样做。 第一种解决方案是更加pythonic和可重复使用。