Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python flask how to allow a user to re-arrange list items and record in database

I have a flask sqlalchemy bootsrap app. My template renders a list of items in a table that I would like the user to be able to rearrange. The items get displayed through standard jinja2

 {% for item in List %}
 {{item}}
  {%end for%}

so how can i allow the user to rearrange the order of the objects and then record those changes?

One idea i had was to get jquery sortable to allow re-arranging and then send the new values to my database (either upon submit, or as they are re-arranged).

But, how do i write a sqlalchemy statement to update the appropriate row in my database? What is the piece between javascript and python where I identify which row in the db to change?

like image 596
Chet Meinzer Avatar asked Oct 18 '25 13:10

Chet Meinzer


1 Answers

jQuery UI's sortable has a toArray message - when it is called on a sortable it returns the IDs of the elements in the order they appear in the DOM. This is probably the simplest way to handle things:

<ul id="theSortableStuff">
{% for item in things_to_sort %}
    <li id="item-{{ item.id }}">{{ item.name }}</li>
{% endfor %}
</ul>

<script>
var $sortables = $("#theSortableStuff").sortable({
  stop: function() {
    var sortedItems = $sortables.sortable("toArray");
    // Update some form in the DOM or use AJAX to invoke a server-side update
  }
});
</script>
like image 159
Sean Vieira Avatar answered Oct 20 '25 04:10

Sean Vieira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!