[英]Sorting items by drag and drop in django
在我的 Django 項目中,我在模板中顯示了書籍列表。 書籍模型具有我用來對書籍進行排序的位置字段。
我正在嘗試通過拖放列表項對這個列表進行排序,但我的下一個代碼不能正常工作。 我使用JQuery UI 。 它在前端工作,但在用戶拖放列表項時不會更改位置字段的值。 有人可以幫助我改進我的 js 並查看代碼。 我很困惑。 我將不勝感激任何幫助。
模型.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']
html:
<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>
網址.py:
url(r'^book/(?P<pk>\d+)/sorting/$',
BookSortingView.as_view(),
name='book_sorting')
JS:
$("#books").sortable({
update: function(event, ui) {
var information = $('#books').sortable('serialize');
$.ajax({
url: "???",
type: "post",
data: information
});
},
}).disableSelection();
視圖.py:
class BookSortingView(View):
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super(BookSortingView, self).dispatch(request, *args, **kwargs)
def post(self, request, pk, *args, **kwargs):
for index, pk in enumerate(request.POST.getlist('book[]')):
book = get_object_or_404(Book, pk=pk)
book.position = index
book.save()
return HttpResponse()
這對我有用!!
JS
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$("tbody").sortable({
update: function(event, ui) {
sort =[];
window.CSRF_TOKEN = "{{ csrf_token }}";
$("tbody").children().each(function(){
sort.push({'pk':$(this).data('pk'),'order':$(this).index()})
});
$.ajax({
url: "{% url "book-sort" %}
",
type: "post",
datatype:'json',
data:{'sort':JSON.stringify(sort),
'csrfmiddlewaretoken': window.CSRF_TOKEN
},
});
console.log(sort)
},
}).disableSelection();
});
HTML
<table class="table table-hover" id="sortable" style="">
<thead>
<tr>
<th></th>
<th>Name</th>
</thead>
<tbody id="#Table">
{% for book in books %}
<tr data-pk="{{ book.id }}" class="ui-state-default" style="cursor: move;" data-placement="left" title="Customize the order by drag and drop">
<td> <a>{{ book.name }}</a> </td>
{% endfor %}
</tbody>
</table>
查看
@csrf_exempt
def sort(self):
books = json.loads(self.request.POST.get('sort'))
for b in books:
book = get_object_or_404(Book, pk=int(b['pk']))
book.position = b['order']
book.save()
return HttpResponse('saved')
並更改列表視圖中的 query_set 以按該順序獲取書籍
books = Book.objects.all().order_by('position')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.