簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM