【发布时间】:2021-04-19 13:24:17
【问题描述】:
下面的代码出现错误AttributeError: 'WSGIRequest' object has no attribute 'request'。我想使用 JQuery sortable.js 拖放重新排序对象的位置。
拖放前端工作正常,但是当我的代码尝试保存对象位置时,我收到错误'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();
});
【问题讨论】:
-
您想在数据库中重新排序它们还是仅在显示它们时重新排序?
-
你能显示这个方法是在哪个类中编写的吗?该错误意味着类 self 可能是这里的请求对象。
-
@AbdulAzizBarkat 它不是一个类,它是一个函数亲爱的。 This is what is want to do
-
那么Sirwill98给出的答案解决了你的错误。对于 pk 的错误,您需要显示您的 js 模板
-
我的问题已更新,请查看...现在出现错误
the JSON object must be str, bytes or bytearray, not NoneType
标签: javascript python django django-views