如何在Django中访问表单提交按钮值? [英] How can I access the form submit button value in Django?

查看:161
本文介绍了如何在Django中访问表单提交按钮值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django项目,在一个页面上,该项目具有多种形式(使用不同的标签),可以提交以产生不同的效果。在所有情况下,我都希望用户被重定向回同一页面,因此在我看来,我使用提交表单然后重定向到原始页面的模式。至少在两种情况下,两种形式之间的唯一区别是提交按钮的值。

I have a Django project that, on one page, has multiple forms (in different tags) that can be submitted to have different effects. In all cases I want the user to be redirected back to the same page, so I use in my view the pattern of submitting the form and then redirecting to the original page. In at least one case, the only difference between two of the forms is the value of the submit button.

在我看来,我有代码(这是第一次我的视图函数访问 request.POST ):

In my view I have the code (which is the first time my view function accesses the request.POST):

if request.POST['submit']=='Add':
    #code to deal with the "Add" form


$ b的代码$ b

,在模板中,第一个表单具有一个提交按钮,例如

and in the template, the first form has a submit button like

<input type="submit" value="Add">

我以为这样可以,但是当我提交该表格时,在该行出现错误从上面查看:

I thought this would work, but when I submit that form, I get an error at the line in view from above:


< QueryDict中找不到关键字'submit':{u'clientyear':[ u'2012'],u'csrfmiddlewaretoken':[u'be1f2f051f09f6ab0375fdf76cf6a4d7'],u'ben':[u'123405']}>

显然,它没有'submit'键或任何键,其值与我单击的提交按钮相对应。因此,由于这不起作用,如何访问提交按钮的值或判断已提交了哪些表单?

Obviously, this does not have a 'submit' key or any key with the value corresponding to the submit button I clicked. So, since this does not work, how can access the value of the submit button or tell which of the forms has been submitted?

推荐答案

提交是HTML表单结构...您必须使用表单对象的name属性,如下所示...在模板中:

Submit is an HTML Form structure... You must use name attribute of form objects as follows... In your template:

<form>
...
<input type="submit" name="list" value="List Objects" />
</form>
<form>
...
<input type="submit" name="do-something-else" value="Do Something Else" />
</form>

您认为:

if 'list' in request.POST:
    # do some listing...
elif 'do-something-else' in request.POST:
    # do something else

这篇关于如何在Django中访问表单提交按钮值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆