javascript - 在 django 中通过拖放对项目进行排序

标签 javascript jquery python django jquery-ui

在我的 django 项目中,我在模板中显示了书籍列表。 Book 模型有 position 字段,我用它来对书籍进行排序。

我正在尝试通过拖放列表项对此列表进行排序,但我的下一个代码无法正常工作。我使用 JQuery UI。它在前端工作,但当用户拖放列表项时不会更改位置字段的值。有人可以帮助我改进我的js并查看代码吗?我很困惑。如果有任何帮助,我将不胜感激。

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

还可以更改 ListView 中的 query_set 以按该顺序获取书籍

 books = Book.objects.all().order_by('position')

关于javascript - 在 django 中通过拖放对项目进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45719681/

相关文章:

javascript - Ember : handling multiple events with {{action}} tag?

javascript - 将 'Reveal All' 按钮替换为 'Reveal Less' onClick?

javascript - 使用 JavaScript 将 Xml 转换为 HTML5

javascript - jQuery 模板插件还是自定义函数?

javascript - 限制可见输入区域中的文本

python - 如何从 virtualenv 中的 python 脚本运行 Tensorboard?

python - 让python在命令行中运行一个文件,输入一些东西,等待然后再次输入一些东西

javascript - 如何从 server.js 获取值到 Node Js 和化合物上应用程序目录中的 Controller

javascript - jQuery 自动完成 ui - 真的很奇怪 1 个字母延迟吗?

python - Scikit 的管道 - 如何访问特定阶段的结果