Referencing multiple submit buttons in django
Give the input types a name and look for them in your request.POST
dictionary.
E.g.:
<form action="/" method="post">
{% csrf_token %}
<input type="text" name="{{ email.id }}" value=" {{email}}"></td>
<td><input type="submit" value="Edit" name="_edit"></td>
<td><input type="submit" value="Delete" name="_delete"></td>
</tr>
and in views.py something like
if request.POST:
if '_edit' in request.POST:
do_edit()
elif '_delete' in request.POST:
do_delete()
EDIT: Changed d.has_key(k)
to k in d
per Daniel's comment. has_key
is deprecated in python 3.0 and the in style is preferred as its more generic -- specifically d.has_key(k)
fails if d isn't a dictionary, but k in d
works for any d
that's an iterable (e.g., dict, string, tuple, list, set).
I know this question was asked a long time ago, but for the record here is a solution using class-based views. It uses the same html as in dr jimbob's answer.
from django.views.generic.edit import FormView
class MyView(FormView):
template_name = 'mytemplate.html'
form_class = MyForm
def form_valid(self, form):
if '_delete' in self.request.POST:
# do delete
elif '_edit' in self.request.POST:
# do edit
Note the default behavior of form_valid
is:
return HttpResponseRedirect(self.get_success_url())