Django add / remove form without multiple submit

前端 未结 3 793
旧巷少年郎
旧巷少年郎 2021-01-15 00:01

I want a simple edit / remove form in Django.

I want it to look like:

Item A   edit  /   remove
Item B   edit  /   remove
Item C   edit  /   remove
<         


        
相关标签:
3条回答
  • 2021-01-15 00:20

    You would probably do better not using a Form to achieve this, as there are (from what you've described) no form elements required.

    Instead you could have a setup in which your urls.py has 2 urls,

    url(r'^app/edit/(?P<id>.*)$', edit_view, name='item_edit'),
    url(r'^app/remove/(?P<id>.*)$', remove_view, name='item_remove'),
    

    And the interface you described above is generated by a template which simply uses {% url %} tag to make hyperlinks to those addresses. Say, for example, you are passing the variable 'items' in your context, you template code would look like this

    <table>
    {% for item in items %}
        <tr>
          <td>{{item.name}}</td>
          <td>{% url 'item_edit' item.id %}</td>
          <td>{% url 'item_remove' item.id %}</td>
        </tr>
    {% endfor %}
    </table>
    

    ...or something to all that effect...

    0 讨论(0)
  • 2021-01-15 00:24

    I did something like this for a similar problem: put this javascript in your template:

    <script language="javascript">function submit(item_id){
    document.myform.item_to_delete.value = item_id;
    document.myform.submit();
    }
    </script>
    

    use your template to create this delete hyperlink for each item:

    <a href="javascript:submit({{ item_id }});">Delete</a>
    

    put this hidden form somewhere on your page:

    <form name="myform" method="post" action="/view_to_handle_delete/"><input name="item_to_delete" type="hidden" value=""></form>'
    

    basically, each item will have a delete hyperlink which calls the js submit function and passes the item to delete. The js function submit sets a hidden input value to this item, then submits the form with that input thereby passing the value via POST to the url /view_to_handle_delete/, and there you handle it like a normal post request. Here the item_id will be called item_to_delete.

    0 讨论(0)
  • Create separate form elements for each entry. Include the item.id as a hidden field as you iterate over each item's form in the template.

    This is a simple way to use POST-based delete over multiple items, important if you'd like to prevent CSRF attacks.

    0 讨论(0)
提交回复
热议问题