问题
In a template I have two connected lists, one of which is initially empty. The user has to choose up to three options from the left list, add them to the right list, order them (according to his/her priorities) and then send it back.
it looks like:
<ul id="sortable1" class="connectedSortable">
<li value="1">Item A</li>
<li value="2">Item B</li>
<li value="3">Item C</li>
<li value="4">Item D</li>
<li value="5">Item E</li>
<li value="6">Item F</li>
<li value="7">Item G</li>
</ul>
</div>
<ul id="sortable2" class="connectedSortable">
<!--here goes the initially empty list-->
</ul>
and in {% scripts %} block:
<script>
$( function() {
$( "#sortable1, #sortable2" ).sortable({
connectWith: ".connectedSortable"
}).disableSelection();
} );
</script>
in models.py I have a field to store the selected info:
preferences = CommaSeparatedIntegerField()
The problem is how to POST info from the updated ul (sortable2
) back to the database? I can add a hidden field preferences
to the page and then fill it using jQuery, but it seems like an ugly solution. What is the right one?
回答1:
If you want to POST the updated ul (sortable2) back to the database, then one of the possible solution is that the ul (sortable2) should be inside a form whose data you can submit using POST method.
Now when any of the li element is moved from the ul (sortable1) to ul(sortable2), then an input type element is also inserted in the ul (sortable2) along with the list element, where "value" attribute of the input will have to be the same as the li element in the ul (sortable1) was. Also the type of this input element will be hidden.
So now when you'll submit this form using a submit button, you'll get all the data back in your views and hence can make changes to your database accordingly.
来源:https://stackoverflow.com/questions/38452150/send-a-list-of-ul-to-form-in-django