Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the form submit button value in Django?

Tags:

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.

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 

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:

Key 'submit' not found in <QueryDict: {u'clientyear': [u'2012'], u'csrfmiddlewaretoken': [u'be1f2f051f09f6ab0375fdf76cf6a4d7'], u'ben': [u'123405']}>

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?

like image 722
murgatroid99 Avatar asked May 15 '12 18:05

murgatroid99


1 Answers

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> 

In your view:

if 'list' in request.POST:     # do some listing... elif 'do-something-else' in request.POST:     # do something else 
like image 196
FallenAngel Avatar answered Oct 01 '22 23:10

FallenAngel