我有点晚了,但这是解决方案
您面临的问题
您正在尝试获取按钮名称,但获取按钮的初始值不正确。
HTML 代码
<input type="submit" value="Add">
Python 代码/View.py
if request.POST['submit']=='Add':
#code to deal with the "Add" form
解决方案
如果存在,首先在 request.POST 字典中找到按钮名称,然后获取它们的值。
HTML 代码
添加按钮的名称及其值。
<input type="submit" value="Add" name="add_object">
视图.py
您可以在 request.POST 字典中找到按钮名称
if request.POST['submit'] == 'add_object':
# Both ways to deal with it
if 'add_object' in request.POST:
额外的东西
我们在一个页面上有两个表单。
第一种形式有 2 个按钮,主题名称相同,但值不同fav_HTML和fav_CSS。
第二种形式也有 2 个按钮,同名tutorials但值不同
Tutorials_HTML和Tutorials_CSS。
<form action="" method="post">
Form 1
<button name="subject" type="submit" value="interview_HTML">HTML</button>
<button name="subject" type="submit" value="interview_CSS">CSS</button>
</form>
<form action="" method="post">
Form 2
<button name="tutorials" type="submit" value="Tutorials_HTML">HTML</button>
<button name="tutorials" type="submit" value="Tutorials_CSS">CSS</button>
</form>
视图.py
我们可以处理不同的表单,检查单击了哪个按钮,然后获取它们的值并做一些事情。
if 'subject' in request.POST: # this section handle subject form (1st Form)
#now we can check which button is clicked
# Form 1 is submitted , button value is subject now getting their value
if 'interview_HTML' == request.POST.get('subject'):
pass
# do something with interview_HTML button is clicked
elif 'interview_CSS' == request.POST.get('subject'):
pass
# do something with interview_CSS button is clicked
elif 'tutorials' in request.POST: #this section handle tutorials form (2nd form)
#now we can check which button is clicked
# Form 1 is submitted , button name is tutorials now getting their value
if 'Tutorials_HTML' == request.POST.get('tutorials'):
pass
# do something with fav_HTML button is clicked
elif 'Tutorials_CSS' == request.POST.get('tutorials'):
pass
# do something with fav_CSS button is clicked