简体   繁体   English

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

[英]Django -> 'WSGIRequest' object has no attribute 'data' -> Error in json.loads(request.data)

I saw a similar question but the answer is rather vague.我看到了一个类似的问题,但答案很模糊。 I created a function based view for updateItem.我为 updateItem 创建了一个基于 function 的视图。 I am trying to get json data to load based on my request.我正在尝试根据我的请求加载 json 数据。 but am getting the error -> object has no attribute 'data'但出现错误 -> object 没有属性“数据”

Views.py file:视图.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 File:文件:

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

urls python file:网址 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"),
]

The Error seems to also occur in my fetch function in the JS file.错误似乎也发生在我在 JS 文件中获取 function 中。 With my method POST.用我的方法 POST。 Can't find a solution, what am I doing wrong here?找不到解决方案,我在这里做错了什么?

The main problem is that you are trying to access 'request.data', there is no such attribute.主要问题是您正在尝试访问“request.data”,没有这样的属性。 What you want is to retrieve data from the POST request.您想要的是从 POST 请求中检索数据。 (Also, note that good practice is to have your views and variable names in snake_case form, whereas camelCase is used for classes): (另外,请注意,好的做法是让您的视图和变量名称采用snake_case形式,而camelCase用于类):

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

Although, to complete my answer, I must say that I had problems with your JS function, with the csrf token not being properly attached.虽然,为了完成我的回答,我必须说你的 JS function 有问题,没有正确附加 csrf 令牌。 My test solution:我的测试解决方案:

views.py视图.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网址.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 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 %}

Try:尝试:

data = json.loads(request.body)

Because the request doesn't have data , since you pass the data as body: JSON.stringify({ productId: productId, action: action }),因为请求没有data ,因为您将数据作为body: JSON.stringify({ productId: productId, action: action }),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 DRF request.data 没有属性 _mutable - DRF request.data has no attribute _mutable Django: AttributeError at /update_item/ 'WSGIRequest' object 没有属性 'data' - Django: AttributeError at /update_item/ 'WSGIRequest' object has no attribute 'data' AttributeError:“ str”对象没有属性“ loads”,json.loads() - AttributeError: 'str' object has no attribute 'loads', json.loads() Django错误:“ WSGIRequest”对象没有属性“ user” - Django Error : 'WSGIRequest' object has no attribute 'user' Django Rest request.data对象为空 - Django Rest request.data object empty Django:AttributeError at /course/u/update-item/ 'WSGIRequest' object 没有使用 django 的属性 'data' - Django: AttributeError at /course/u/update-item/ 'WSGIRequest' object has no attribute 'data' using django 应用了base64解码的数据在json.loads()中出错 - Error in json.loads() for data that has base64 decoding applied Django 测试用例错误 &#39;WSGIRequest&#39; 对象没有属性 &#39;session&#39; - Django Test Case Error 'WSGIRequest' object has no attribute 'session' Django管理错误&#39;WSGIRequest&#39;对象没有属性&#39;user - Django admin error 'WSGIRequest' object has no attribute 'user Ajax-ing JavaScript变量到Django视图获取:AttributeError:&#39;WSGIRequest&#39;对象没有属性&#39;data&#39; - Ajax-ing JavaScript variable to Django view getting: AttributeError: 'WSGIRequest' object has no attribute 'data'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM