在Django中通过拖放对项目进行排序 [英] Sorting items by drag and drop in django

查看:261
本文介绍了在Django中通过拖放对项目进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的django项目中,我显示了模板中的书籍列表. Book 模型具有 position 字段,可用于对图书进行排序.

In my django project I show a list of books in template. Book model has position field which I use to sort books.

我正在尝试通过拖放列表项对该列表进行排序,但是我的下一个代码不能很好地工作.我使用 JQuery UI .它在前端工作,但在用户拖放列表项时不更改位置字段的值.有人可以帮助我改善我的js并查看代码.我很困惑.我将不胜感激.

I'm trying to sort this list by drag and drop list items but my next code dont work well. I use JQuery UI. It works in frontend but dont change position field`s value when user drag and drop list item. Can someone help me to improve my js and view code. I am comfused. I would be grateful for any help.

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']

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>

urls.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();

views.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')

这篇关于在Django中通过拖放对项目进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆