Alex Rivera | Logout

Referencing multiple submit buttons in django

Asked 2011-05-04T03:22:23.023
20

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?

Edit
Report

1 Answer

40

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).

answered 2011-05-04T03:27:48.010

Your Answer