Django request.POST 不包含提交表单的按钮的名称 [英] Django request.POST does not contain the name of the button that submitted the form
问题描述
我有一个带有两个不同提交按钮的 Django 表单,在提交表单的视图上,我需要知道按下了什么提交按钮并相应地采取不同的操作.
I have a django form with two different submit buttons, on the view where the form is submitted to I need to know what submit button was pressed and take different actions accordingly.
据我所知,提交按钮的名称或 ID 应该在 request.POST 字典中的某处,但它不在那里!
From what I have read the submit button's name or id should be somewhere in the request.POST dictionary, but it not there!
这是我的表格片段:
<form id="editPaperForm" action="{{paper.editURL}}" method="POST">
<input type="submit" name="savePaperButton" id="savePaperButton" value="Save and Send Later"/>
<input type="submit" name="sendPaperButton" id="sendPaperButton" value="Save and send"/>
...
</form>
在视图中:
...
if 'sendPaperButton' in request.POST:
return applicants_confirmSend(request, paperID)
else:
return applicants_home(request)
sendPaperButton 永远不会出现在 request.POST 中,另一个也不是,我应该寻找其他地方吗?
sendPaperButton is never in the request.POST, and neither is the other one, should I be looking somewhere else?
我唯一的想法是在发送表单之前添加一个隐藏字段并通过 javascript 修改它,但这似乎有点多余,因为我很确定数据应该在某处......
The only idea I have is to add a hidden field and modify it via javascript before sending the form but that seems kind of redundant since I'm pretty sure that data should be there somewhere...
谢谢!
推荐答案
不要忘记将名称和值参数添加到表单的按钮"或输入类型=提交"字段中.我曾经遇到过同样的问题,这让我发疯了.
Don't forget to add the name and value parameters to your "button" or "input type=submit" fields of the form. I've had the same problem once and it drove me crazy.
简而言之,由于 request.POST 包含一个 dict,您需要一个键和一个值.键对应按钮的名称参数,字典的值对应按钮的值.
In short, as request.POST contains a dict, you need a key and a value. The key corresponds to the name parameter of your button, and the dict's value to the button's value.
<button type="submit" value="preview">Preview</button>
不会反映在 request.POST 中(POST 字典没有键!),而
won't be reflected in request.POST (there's no key for the POST dictionary!), whereas
<button type="submit" value="preview" name="preview">Preview</button>
将有一个值为preview"的键preview".
will have a key "preview" with value "preview".
这篇关于Django request.POST 不包含提交表单的按钮的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!