在Django views.py中处理表单POST时,它似乎忽略了HttpResponse类型

问题描述 投票:0回答:1

我有一个生成数据表的Django应用程序。我有一个表单,您可以在其中输入参数,单击一个按钮查看结果,或单击另一个按钮下载CSV。看到结果是有效的,但下载CSV不是。

我在views.py中处理响应,设置内容类型和处置,并返回响应。它不是下载CSV,而是将数据显示为文本。 (我尝试了StreamingHttpResponse和普通的HttpResponse。)处理传递参数的URL时,完全相同的代码。所以,我尝试了一个HttpResponseRedirect,它没有做任何事情。我甚至尝试重定向到一个普通的URL,没有任何效果。我认为响应类型被忽略了,但我不知道为什么。

HTML:

<form action="" method="post" class="form" id="form1">
{{ form.days }} {{ form.bgguserid }}
<input type="submit" value="Go!" id="button-blue"/>
<input type="submit" name="csv-button" value="CSV" id="csv-button"/>
</form>

views.py尝试1:

def listgames(request, bgguserid, days=360):
    if 'csv-button' in request.POST:
        # create CSV in variable wb
        response = StreamingHttpResponse(wb, content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="collectionvalue.csv"'
        return response

尝试2,相同但有:

response = HttpResponseRedirect ('/collection/{0}/csv/{1}/'.format(bgguserid,days))

我对其他解决方案持开放态度,比如客户端重定向到正常运行的URL,但我不想丢失表单验证,而且我的HTML / javascript技能很弱。

python django csv httpresponse html-form-post
1个回答
0
投票

我解决了这个问题。 views.py中的代码(我从某处复制)是从表单处理方法的返回值创建一个新的HttpRequest对象。

def indexform(request):
   if request.method == 'POST':
        form = IndexForm(request.POST)
        # Check if the form is valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            response = listgames(request, bgguserid=form.cleaned_data['bgguserid'], days=form.cleaned_data['days'])
            # redirect to a new URL:
            return HttpRequest(response)

通过将最后一行更改为仅返回响应,它可以按预期工作。很抱歉浪费任何人的时间。

© www.soinside.com 2019 - 2024. All rights reserved.