How would I call on the following multiple submit forms --
<form action="/" method="post">
{% csrf_token %}
<input type="text" name="{{ email.id }}" value=" {{email}}"></td>
<td><input type="submit" value="Edit"></td>
<td><input type="submit" value="Delete"></td>
</tr>
</form>
I want to do something like this --
if value = edit:
do this
if value = delete:
do this
How would I code this in the views.py file?
Let's learn the steps of performing multiple actions with multiple buttons in a single HTML form: Create a form with method 'post' and set the value of the action attribute to a default URL where you want to send the form data. Create the input fields inside the as per your concern. Create a button with type submit.
yes, multiple submit buttons can include in the html form. One simple example is given below.
Put a hidden field. And when one of the buttons are clicked before submitting, populate the value of hidden field with like say 1 when first button clicked and 2 if second one is clicked. and in submit page check for the value of this hidden field to determine which one is clicked. Show activity on this post.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With