简体   繁体   English

如何重新排序 Django 中对象的 position?

[英]How to Reorder the position of objects in Django?

The code below is getting error AttributeError: 'WSGIRequest' object has no attribute 'request' .下面的代码出现错误AttributeError: 'WSGIRequest' object has no attribute 'request' I want to reOrder the position of objects using JQuery sortable.js Drag and drop.我想使用 JQuery sortable.js 拖放来重新排序对象的 position。 the drag and drop frontend is working fine but when my code try to save the object position i'm getting the error 'WSGIRequest' object has no attribute 'request' .拖放前端工作正常,但是当我的代码尝试保存 object position 时,我收到错误'WSGIRequest' object has no attribute 'request' I would be grateful for any help.如果有任何帮助,我将不胜感激。

@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 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 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();
    });

have you tried this?你试过这个吗? (replacing self with request and using request instead of self.request (用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM