Django ->'WSGIRequest'对象没有属性'data' ->json.loads中的错误(request.data)

wbrvyc0a  于 2022-12-14  发布在  Go
关注(0)|答案(2)|浏览(222)

我看到了一个类似的问题,但答案相当模糊。我为updateItem创建了一个基于函数的视图。我试图根据我的请求加载json数据。但我得到了错误-〉对象没有属性'data'
Views.py 文件:

def updateItem(request):  
    
    data = json.loads(request.data)
    
    productId = data['productId']
    action = data['action']
    print("productID", productId, "action", action)
    customer = request.user.customer
    product = Product.objects.get(id=productId)
    order, created = Order.objects.get_or_create(customer=customer,complete=False)

    orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)
    
    
    if action == 'add':
        orderItem.quantity = (orderItem.quantity + 1)
    elif action == 'remove':
        orderItem.quantity = (orderItem.quantity - 1)
    orderItem.save()
    
    if orderItem.quantity <= 0:
        orderItem.delete()
        
    return JsonResponse("Item was added!", safe=False)

JS文件:

function updateUserOrder(productId, action) {
    console.log('User is logged in...');
    let url = '/update_item/';

    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': csrftoken,
        },
        body: JSON.stringify({ productId: productId, action: action }),
    })
        .then((res) => {
            return res.json();
        })
        .then((data) => {
            console.log('data', data);
        });
}

网址python文件:

urlpatterns = [
    path("",views.store,name="store"),
    path("cart/",views.cart,name="cart"),
    path("checkout/",views.checkout,name="checkout"),
    path("update_item/",views.updateItem,name="update_item"),
]

这个错误似乎也发生在我的JS文件的fetch函数中。用我的方法POST。找不到解决方案,我在这里做错了什么?

cdmah0mi

cdmah0mi1#

试试看:

data = json.loads(request.body)

因为请求没有data,因为您将数据作为body: JSON.stringify({ productId: productId, action: action }),传递

v1l68za4

v1l68za42#

主要的问题是您正在尝试访问“request.data”,但没有这样的属性。您想要的是从POST请求中检索数据。(另外,请注意,最好的做法是将视图和变量名设置为snake_case格式,而将camelCase用于类):

def updateItem(request):  
    
    data = json.loads(request.POST.get('data'))
    ...
        
    return JsonResponse("Item was added!", safe=False)

尽管如此,为了完成我的回答,我必须说我的JS函数有问题,因为csrf令牌没有正确附加。
views.py

from django.shortcuts import render
from django.http import JsonResponse
import json

def update_item(request):
    return render(request, 'update_item.html', {})

def update_item_ajax(request): 
    data = json.loads(request.POST.get('data'))
    print(data)
    ...
    
    return JsonResponse({'message': '"Item was added!"'}, safe=False)

# output of update_item_ajax print
{'productId': 1, 'action': 'myaction'}

urls.py

from django.urls import path
from core import views

app_name = 'core'

urlpatterns = [
    path('update/item/', views.update_item, name='update-item'),
    path('update/item/ajax/', views.update_item_ajax, name='update-item-ajax'),
]

update_item.html

{% extends 'base.html' %}

{% block content %}
<button onclick="updateUserOrder(1, 'action')"> update item </button>
{% endblock %}

{% block script %}
    <script>
        function updateUserOrder(productId, action) {
            console.log('User is logged in...');
            let url = "{% url 'core:update-item-ajax' %}";
            
            var payload = {
                productId: productId,
                action: action
            };
            var data = new FormData();
            data.append( 'data' , JSON.stringify( payload ) );
            data.append('csrfmiddlewaretoken', '{{ csrf_token }}');

            fetch(url, 
            {   
                method: 'POST',
                body: data,
            })
            .then(function(res){ return res.json(); })
            .then(function(data){ console.log(data); });
        }
    </script>
{% endblock %}

相关问题