Using Django and Jquery



除了这篇文章 https://stackoverflow.com/a/17732956 我想通过拖放更改列表的顺序,然后将其保存在 django 后端。

出于测试目的和理解,我使用了以下小提琴:

http://jsfiddle.net/LvA2z/#&togetherjs=LvHpjIr7L0

并用我自己的动作更新了表单的动作。因此,我使用了action="{% url 'save_order' %}",而不是script.php"。

在视图中,我的函数如下所示:

def save_order(request):
if (request.method == 'POST'):
list = request.POST['listCSV']
print(list)

基本上我想更改列表元素的顺序并在之后保存它,结果是在刷新页面后给出保存的顺序。但是我不知道,如何将变量从jquery传递到django站点。当我更改顺序时,我在"listCSV"中有排序列表。如何将此结果传递给 django 站点以将其保存在数据库中?

编辑: 如果//$("#listsaveform").submit();没有被注释掉,我触发了用我的save_order函数引用的这个函数,我得到了这个错误:

jquery-1.10.2.min.js:6 POST http://localhost:8000/overview/saveOrder/405(方法不允许)

编辑:

好的,谢谢你的提示。我从未使用过ajax,因此我有点卡住了。 我有我的列表结构:

{% if habits %}
<ul id="sortable">
{% for habit in habits|dictsort:"priority" %}
<li class="ui-state-default">{{habit.title}}</li>
{% endfor %}
</ul>
{% endif %}

这个列表结构可以用以下代码行进行排序:

$(function() {
$( "#sortable" ).sortable();
});

我的形状看起来如何?

这是我基于 https://impythonist.wordpress.com/2015/06/16/django-with-ajax-a-modern-client-server-communication-practise/的解决方案。

在 JS 中

// Sort & save order of habits
$(function () {
$('.sort').sortable({
handle: 'button',
cancel: '',
update: function(event, ui) {
var result = $(this).sortable( "serialize", {key: event.target.id});
// alert(result);
var csrftoken = getCookie('csrftoken');
$.ajax({
url : "/overview/saveOrder/", // the endpoint,commonly same url
type : "POST", // http method
data : { csrfmiddlewaretoken : csrftoken,
result : result,
}, // data sent with the post request
// handle a successful response
success : function(json) {
console.log(json); // another sanity check
//On success show the data posted to server as a message
//  alert('Your list '+json['result']);
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
console.log("FAILURE");
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
}
});
// var sorted = $( ".selector" ).sortable( "serialize", { key: "sort" } );
// console.log(sorted)
})
//For getting CSRF token
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}

而在姜戈方面

def save_habit(request):
print('save_habit')
if (request.method == 'POST'):
if request.is_ajax():
habits = Habit.objects.filter(created_by=request.user.userprofile, is_active=True)
habit_title = request.POST.get('habit_title')
habit_trigger = request.POST.get('habit_trigger')
habit_routine = request.POST.get('habit_routine')
habit_targetbehavior = request.POST.get('habit_targetbehavior')
habit_image = request.POST.get('habit_image')
print(habit_image)
image = habit_image.split('http://localhost:8000/media')
print(image[1])
# TODO: was,  wenn routine noch gar nicht existiert? --> speichern
obj_routine = Existingroutine.objects.get(name=habit_routine)
obj_targetbehavior = Targetbehavior.objects.get(name=habit_targetbehavior)
for habit in habits:
habit.priority += 1;
# habit.save();
habit = Habit(created_by=request.user.userprofile, is_active=True,
title=habit_title, trigger=habit_trigger, existingroutine=obj_routine,
targetbehavior=obj_targetbehavior, image=image[1])
#habit.save()
data = {"habit_title":habit_title,
"habit_trigger":habit_trigger,
"habit_routine":habit_routine,
"habit_targetbehavior":habit_targetbehavior };
return JsonResponse(data)
return redirect('display_habits')

最新更新