使用ajax POST时Django中的MultiValueDictKeyError

时间:2016-04-04 20:04:22

标签: ajax django

我正在使用ajax post但是得到了MultiValueDictKeyError。这是一个购物车,我可以点击这个项目添加产品。

models.py

   class Product(models.Model):
        title = models.CharField(max_length=100,unique=True)
        description = models.TextField()
        image_url = models.URLField(max_length=200)
        price = models.DecimalField(max_digits=8,decimal_places=2)
   class LineItem(models.Model):
         product = models.ForeignKey(Product)
         unit_price = models.DecimalField(max_digits=8,decimal_places=2)
         quantity = models.IntegerField()

serializers.py

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ('id',)
class LineItemSerializer(serializers.ModelSerializer):
    product = ProductSerializer()
    class Meta:
        model = LineItem
        fields = ('product', 'unit_price', 'quantity')

views.py

class RESTforCart(APIView):

def get(self, request, *args, **kwargs):
    lists=request.session['cart'].items 
    serializer = LineItemSerializer(lists,many=True)
    return Response(serializer.data)
def post(self, request, format=None):
    id=request.data["product"]["id"]
    product = Product.objects.get(id=id)
    cart = request.session['cart']
    cart.add_product(product)
    request.session['cart'] = cart
    lists=request.session['cart'].items 
    serializer = LineItemSerializer(lists,many=True)
    return Response(serializer.data)

urls.py

(r'^API/cart/items/$', RESTforCart.as_view()),

我的可浏览API效果很好: Please click to see my browsable API

提交内容为
{         "产品":{             " id":1         },         " unit_price":" 12.00",         "数量":2  }

但是当我使用

$.post("/depotapp/API/cart/items/", { product: {  id: 1 , },  unit_price: "12.00",  quantity: 18, },function(data){ console.log(data);});

在我的js文件中,在/ depotapp / API / cart / items /获取MultiValueDictKeyError "'产品'" please click to review error message

1 个答案:

答案 0 :(得分:0)

将其修复为views.py

id=request.data["product[id]"]