Skip to content

Instantly share code, notes, and snippets.

@makmac213
Created August 2, 2013 03:36
Show Gist options
  • Save makmac213/6137323 to your computer and use it in GitHub Desktop.
Save makmac213/6137323 to your computer and use it in GitHub Desktop.
# the javascript #
"""
var position = -1;
$(function(e) {
$("#sortable").sortable({
start: function(event, ui) {
position = ui.item.index();
},
stop: function(event, ui) {
//alert("New position: " + ui.item.index());
if(position!=ui.item.index()) {
postData = {
old_position : position,
new_position : ui.item.index()
};
$.post('{% url change_article_position %}',
postData,
function(data) {
position = ui.item.index();
location.reload();
}
);
}
}
});
$("#sortable" ).disableSelection();
});
"""
# urls.py
url(r'^admin/article/change/position/ajax/$', 'change_article_position', {}, name="change_article_position"),
# views.py
def change_article_position(request):
return _change_model_position(request, Article)
def _change_model_position(request, model):
if request.method == 'POST':
old_position = int(request.POST.get('old_position')) + 1;
new_position = int(request.POST.get('new_position')) + 1;
current_item = model.objects.get(position=old_position)
current_item.order = new_position
current_item.save()
if new_position < old_position:
greater_items = model.objects.filter(
~Q(pk=current_item.id),
position__gte=current_item.order).order_by('position')
ctr = current_item.order + 1
for item in greater_items:
item.position = ctr
item.save()
ctr += 1
else:
lesser_items = model.objects.filter(
~Q(pk=current_item.id),
position__lte=new_position).order_by('position')
ctr = 1
for item in lesser_items:
item.position = ctr
item.save()
ctr += 1
greater_items = model.objects.filter(
~Q(pk=current_item.id),
position__gt=new_position).order_by('position')
ctr = new_position + 1
for item in greater_items:
item.position = ctr
item.save()
ctr += 1
messages.success(request, _('Position updated'))
return HttpResponse('OK')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment