Nurzhan Nogerbek Nurzhan Nogerbek - 1 year ago 60
Ajax Question

How reorder list items by drag and drop?

In my Django project I show list of books. I am trying to reorder list items by drag and drop. I use next code below but it raise error. Can someone help me to fix it? I am confused.

My aim: Change position field's value when user drag and drop list item.

models.py:

class Book(models.Model):
title = models.CharField(max_length=200, help_text='Title', blank=False)
position = models.IntegerField(help_text='Position', default=0, blank=True)

class Meta:
ordering = ['position', 'pk']


urls.py:

url(r'^book/sorting/$',
BookSortingView.as_view(),
name='book_sorting')


JS:

$("#books").sortable({
stop: function(event, ui) {
book_order = {};
$("#books").children().each(function(){
book_order[$(this).data('pk')] = $(this).index();
});

$.ajax({
url: "{% url 'book_sorting' %}",
type: "post",
contentType: 'application/json; charset= utf-8',
dataType: 'json',
data: JSON.stringify(book_order),
});
}
});


views.py: (P.S. I use the mixins of django-braces app)

class BookSortingView(CsrfExemptMixin, JsonRequestResponseMixin, View):
def post(self, request):
for pk, position in self.request_json.items():
Book.objects.filter(pk=pk).update(position=position)
return self.render_json_response({'saved': 'OK'})


ERROR:

P.S. It seems to me that problem is in this line:
Book.objects.filter(pk=pk).update(position=position)
in views

Traceback (most recent call last):
File "/srv/envs/Project/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/srv/envs/Project/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/srv/envs/Project/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/srv/envs/Project/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/srv/envs/Project/lib/python3.6/site-packages/django/utils/decorators.py", line 67, in _wrapper
return bound_func(*args, **kwargs)
File "/srv/envs/Project/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/srv/envs/Project/lib/python3.6/site-packages/django/utils/decorators.py", line 63, in bound_func
return func.__get__(self, type(self))(*args2, **kwargs2)
File "/srv/envs/Project/lib/python3.6/site-packages/braces/views/_forms.py", line 24, in dispatch
return super(CsrfExemptMixin, self).dispatch(*args, **kwargs)
File "/srv/envs/Project/lib/python3.6/site-packages/braces/views/_ajax.py", line 144, in dispatch
request, *args, **kwargs)
File "/srv/envs/Project/lib/python3.6/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/home/nurzhan/CA/slider/views.py", line 87, in post
Slide.objects.filter(pk=pk).update(position=position)
File "/srv/envs/Project/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/srv/envs/Project/lib/python3.6/site-packages/django/db/models/query.py", line 781, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/srv/envs/Project/lib/python3.6/site-packages/django/db/models/query.py", line 799, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/srv/envs/Project/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1260, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/srv/envs/Project/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1286, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/srv/envs/Project/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1220, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/srv/envs/Project/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1114, in build_lookup
return final_lookup(lhs, rhs)
File "/srv/envs/Project/lib/python3.6/site-packages/django/db/models/lookups.py", line 24, in __init__
self.rhs = self.get_prep_lookup()
File "/srv/envs/Project/lib/python3.6/site-packages/django/db/models/lookups.py", line 74, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "/srv/envs/Project/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 962, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'undefined'


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.id }} - {{ book.title }}</div>
</div>
{% endfor %}
</div>

Answer Source

The problem resides on

book_order[$(this).data('pk')] = $(this).index();

where you're not declaring data-pk to your HTML. Changing to this:

<div id="books" class="list-group">
{% for book in books %}
    <div data-pk="{{ book.id }}" class="panel panel-default ...">
        <div class="panel-body">{{ book.id }} - {{ book.title }}</div>
    </div>
{% endfor %}
</div>

should work. Notice that, now, each div has a data-pk data-attribute inside it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download