Answer the question
In order to leave comments, you need to log in
How to sort a list by drag and drop in Django?
Hello! Please help me figure it out.
In my Django project, I display a list of books on a page. The Book data model has a position field that sorts by. It is necessary to allow the user to sort the list using drag and drop. The question is the following. Has anyone faced a similar issue?
I found a sortable section in JQuery UI , but I don’t quite understand how to connect it with Django, so that when dragging, the value of the position field changes and is saved in the database. Please help me figure it out and point me in the right direction. At the moment everything works only on frontend-e. models.py:
class Book(models.Model):
title = models.CharField(max_length=200, help_text='Заголовок', blank=False)
position = models.IntegerField(help_text='Поле для сортировки', default=0, blank=True)
class Meta:
ordering = ['position', 'pk']
<div id="books" class="list-group">
{% for book in books %}
<div class="panel panel-default list-group-item ui-state-default">
<div class="panel-body">{{ book.title }}</div>
</div>
{% endfor %}
</div>
$( "#books" ).sortable();
Answer the question
In order to leave comments, you need to log in
I don't think it's a good idea to store sorting data in a database. After all, one user can sort this way, and the other differently, and judging by your model, the last sort will be displayed for any user, such things must be stored with the user himself, in a cookie, for example
The sortable plugin has an update event that is called every time the user has dragged an element to a new location. More details here api.jqueryui.com/sortable/#event-update. So it's done something like this:
$( "#books" ).sortable({
update: function( event, ui ) {
// В ui содержится вся необходимая инфа о новой позиции перемещенного элемента
// которую вы можете сохранить в БД аякс-запросом
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question