开发者

Getting the value of an item in a django template for loop

开发者 https://www.devze.com 2023-03-08 02:22 出处:网络
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:

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:

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

  2. 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>
    
  3. 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 with delete-position and then use slicing.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号