Using django, I have a form in which a user enters his 'position'
. The user may add multiple positions. The user may also delete positions. There are two things worth noting with this:
1) in the form, there are two buttons, 'Add'
and 'Delete'
.
2) I am using a for loop in the template to populate the list of positions and delete buttons.
This is what I currently have:
# in template
<tr>
<td>Position</td>
<td>{{ form.position }}
<input type="submit" value="Add" , name='action'/>
</td>
</tr>
<tr>
<td> </td>
<td>
{% for position in positions %}
{{ position}}
<input type="submit" value="Delete 开发者_如何学JAVA{{position }}", name='action'/>
{% endfor %}
</td>
</tr>
# in views.py
...
if action == 'Add':
positions.append(request.POST['position'])
return render_to_response(...)
if 'Delete' in action:
positions.remove(request.POST['action'][7:])
return render_to_response('...)
This seems like a very inelegant way to do the "Deletion" part.
Is there a better way to get the value of the position
, without having to cram in additional information in the 'Delete' submit button
, and then slicing it off to get its value?
I see three options here:
Use checkbox field for each position and one "Delete" button. In that case a user can choose multiple positions to be deleted and you can get their IDs from request easily.
Use a hidden field
position
and a little bit of Javascript to fill it. If you use jquery it could be:<input type="hidden" name="position" value="" /> {% for position in positions %} <input type="submit" value="Delete" name="action" data-position="{{ position }}" />; {% endfor %} <script type="text/javascript"> var $position_input = $("input[name='position']"); $("input[name='action'][value='Delete'].click(function(e) { var $this = $(this); var position = $this.data("position"); $position_input.val(position); }); </script>
Insert position ID into name attribute, like this:
<input type="submit" value="Delete" name="delete-position.{{ position }} />
In view function you'll have to look through all data in
request.POST
and find all items which start withdelete-position
and then use slicing.
精彩评论