简体   繁体   中英

How to Reorder the position of objects in Django?

The code below is getting error AttributeError: 'WSGIRequest' object has no attribute 'request' . I want to reOrder the position of objects using JQuery sortable.js Drag and drop. 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' . 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

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

have you tried this? (replacing self with request and using request instead of 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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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