[英]How to Reorder the position of objects in Django?
下面的代码出现错误AttributeError: 'WSGIRequest' object has no attribute 'request'
。 我想使用 JQuery sortable.js 拖放来重新排序对象的 position。 拖放前端工作正常,但是当我的代码尝试保存 object position 时,我收到错误'WSGIRequest' object has no attribute 'request'
。 如果有任何帮助,我将不胜感激。
@csrf_exempt
def sort(self):
books = json.loads(self.request.POST.get('sort'))
for b in books:
book = get_object_or_404(Article, pk=int(b['pk']))
book.position = b['order']
book.save()
return HttpResponse('saved')
html
<table class="table" style="margin-top: 10px; margin-bottom: 0;">
<thead>
<tr>
<th>ID</th>
<th>Story</th>
<th>Created</th>
<th>Timestamp</th>
</tr>
</thead>
<tbody>
{% for object in articles %}
<tr data-pk="{{ object.id }}">
<td>{{ object.id }}</td>
<td><a href="">{{ object.title }}</a></td>
<td>{{ object.author.username }}</td>
<td>{{ object.updated_on | naturaltime }}</td>
</tr>
{% endfor %}
</tbody>
</table>
js
$(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 'rundown-sort' %}",
type: "post",
datatype: 'json',
data: {
'sort': JSON.stringify(sort),
'csrfmiddlewaretoken': window.CSRF_TOKEN
},
success: function () {
console.log('success')
}
});
console.log(sort)
},
}).disableSelection();
});
你试过这个吗? (用 request 替换 self 并使用 request 而不是 self.request
@csrf_exempt
def sort(request):
books = json.loads(request.POST.get('sort'))
for b in books:
book = get_object_or_404(Article, pk=int(b['pk']))
book.position = b['order']
book.save()
return HttpResponse('saved')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.