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

2024-02-19

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

我试图通过拖放列表项对该列表进行排序,但我的下一个代码不能很好地工作。我用jQuery 用户界面。它在前端工作,但当用户拖放列表项时不会更改位置字段的值。有人可以帮助我改进我的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>

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

视图.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>

view

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

并更改列表视图中的查询集以按该顺序获取书籍

 books = Book.objects.all().order_by('position')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 django 中通过拖放对项目进行排序 的相关文章

随机推荐