【问题标题】:How to Reorder the position of objects in Django?如何在 Django 中重新排序对象的位置?
【发布时间】: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


【解决方案1】:

你试过吗? (用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')

【讨论】:

  • 是的,我也试试这个!当我尝试使用您的代码时,它会得到 keyError Exception Value: 'pk'
  • 似乎book = get_object_or_404(Article, pk=int(b['pk'])) 行抛出错误,json 是什么样的?
  • 这里的 json 看起来像 [{'order': 0}, {'order': 1}, {'pk': 51, 'order': 0}, {'pk': 59,'订单':1},{'pk':61,'订单':2},{'pk':62,'订单':3},{'pk':63,'订单':4} , {'pk': 65, 'order': 5}, {'pk': 64, 'order': 6}, {'pk': 66, 'order': 7}, {'pk': 67, “订单”:8}]
  • 我认为这个错误是因为前 2 个 json 条目没有 PK 值,你能做一个 if 语句来检查一个 pk
  • try: book = get_object_or_404(Article, pk=int(b['pk'])) book.position = b['order'] book.save() except KeyError: pass
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
相关资源
最近更新 更多