在同一个表单中使用多个提交按钮

9

我无法从框架中访问所有按钮,只有直方图按钮可以使用。以下是我的表单,我希望在POST方法中访问它。

 <form id="package_form" action="" method="post">
      <div class="panel-body">
          <input type ="submit" name="Download" value="Download">
      </div>
      <div class="panel-body">
          <input type ="submit" name="Histogram" value="Histogram">
      </div>
      <div class="panel-body">
           <input type ="submit" name="Search" value="Search">
      </div>

 </form>

这是我的Python代码。

 if request.method == 'GET':
        return render_template("preview.html", link=link1)
    elif request.method == 'POST':
        if request.form['Histogram'] == 'Histogram':
            gray_img = cv2.imread(link2,cv2.IMREAD_GRAYSCALE)
            cv2.imshow('GoldenGate', gray_img)
            hist = cv2.calcHist([gray_img], [0], None, [256], [0, 256])
            plt.hist(gray_img.ravel(), 256, [0, 256])
            plt.xlabel('Pixel Intensity Values')
            plt.ylabel('Frequency')
            plt.title('Histogram for gray scale picture')
            plt.show()
            return render_template("preview.html", link=link1)

        elif request.form.get['Download'] == 'Download':
            response = make_response(link2)
            response.headers["Content-Disposition"] = "attachment; filename=link.txt"
            return response
        elif request.form.get['Search'] == 'Search':
            return link1

我做错了什么?
2个回答

33
你的代码写法无法生效。只有发送的提交按钮才会被包含在request.form中,如果你尝试使用其他按钮的名称,则会出现错误。
此外,request.form.get是一个函数,而不是字典。你可以使用request.form.get("Histogram"),这将返回Histogram按钮的值(如果使用了该按钮),否则它将返回None
不要给按钮分配不同的名称,而是使用相同的名称但不同的值。
<form id="package_form" action="" method="post">
      <div class="panel-body">
          <input type ="submit" name="action" value="Download">
      </div>
      <div class="panel-body">
          <input type ="submit" name="action" value="Histogram">
      </div>
      <div class="panel-body">
          <input type ="submit" name="action" value="Search">
      </div>

 </form>

那么你的Python代码可以是:

if request.form['action'] == 'Download':
    ...
elif request.form['action'] == 'Histogram':
    ...
elif request.form['action'] == 'Search':
    ...
else:
    ... // Report bad parameter

我的 request.form 没有 post 属性。在表单本身中找到了这些操作。 - jlplenio
你的表单中是否有一个名为 action 的输入框? - Barmar

8

虽然使用相同的名称来提交不同的内容可以起到作用(就像上一个答案中建议的那样),但这对于国际化可能不是很方便。

您仍然可以使用不同的名称,但应该以不同的方式处理它们:

if 'Download' in request.form:
    ...
elif 'Histogram' in request.form:
    ...
elif 'Search' in request.form:
    ...
else:
    ... // Report bad parameter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接