Django KeyError:';产品标识';
因此,我将跟随youtube课程,创建一个电子商务web应用程序,并根据具体需要进行定制。尝试将product_id分配给product_idDjango KeyError:';产品标识';,django,vue.js,django-rest-framework,Django,Vue.js,Django Rest Framework,因此,我将跟随youtube课程,创建一个电子商务web应用程序,并根据具体需要进行定制。尝试将product_id分配给product_id时,我在api.py文件中遇到了一个KeyError,请参见下面的行:product_id=data['product_id'],来自request.body,但这会中断应用程序,因为它找不到该密钥。进一步检查后,我发现请求主体字典只包含三个变量(“数量”和“更新”)中的两个,缺少“product.id”变量。我很难找出原因。如果有人能帮我解释一下他们的推
时,我在api.py文件中遇到了一个KeyError,请参见下面的行:product_id=data['product_id']
,来自request.body,但这会中断应用程序,因为它找不到该密钥。进一步检查后,我发现请求主体字典只包含三个变量(“数量”和“更新”)中的两个,缺少“product.id”变量。我很难找出原因。如果有人能帮我解释一下他们的推理,那就太好了(我还在学习,所以我不仅想知道答案,还想知道原因)。下面是cart.html和api.py中的Vue代码,以及cart.html代码的views.py文件,这些都是问题所在。谢谢我已经被困在这个相当长的一段时间了,现在想了解和修复这一点,所以我可以继续该项目
cart.html
{% extends 'base.html' %}
{% block title %}Cart | {% endblock %}
{% block content %}
<div id="hero" class="mid">
<div class="hero text-center">
<h2 class=" display-4 font-weight-bold">Cart</h2>
<p class="text-light mx-auto">Finish checkout below</p>
</div>
</div>
<div id="cartapp">
<h1 class="container-fluid title">Cart</h1>
{% if cart %}
<div class="table">
<table class="table">
<thead>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th></th>
</thead>
<tbody>
<tr v-for="product in products" v-bind="product.id">
<td>[[ product.title ]]</td>
<td>[[ product.quantity ]] <button
@click="incrementQuantity( product.id , product.quantity)">+</button></td>
<td>[[ product.total_price ]]</td>
<td><a class="btn btn-lg col-sm-4 " id="text" @click="removeFromCart(product.id)">
Remove from cart
</a></td>
</tr>
</tbody>
</table>
</div>
{% else %}
<p class="text">Your cart is empty</p>
{% endif %}
</div>
{% endblock %}
{% block scripts %}
{{ productsstring|json_script:"json-productsstring" }}
<script>
var cartapp = new Vue({
el: '#cartapp',
delimiters: ['[[', ']]'],
store: store,
data() {
return {
products: JSON.parse(document.getElementById('json-productsstring').textContent)
}
},
mounted() {
console.log('Mounted');
console.log(this.products)
},
methods: {
incrementQuantity(product_id, quantity) {
console.log('Product_id:', product_id);
var data = { 'product_id': product_id, 'update': true, 'quantity': parseInt(quantity) + 1 }
console.log('Quantity', quantity);
store.commit('increment', 1)
fetch('/api/add_to_cart/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token }}'
},
credentials: 'same-origin',
body: JSON.stringify(data)
})
.then((response) => {
console.log(response);
for (var i = 0; i < this.product.length; i++) {
var product = this.product[i];
if (product.id == product_id) {
this.products[i].quantity = parseInt(this.products[i].quantity) + 1;
this.products[i].total_price = parseInt(this.products[i].quantity) * parseFloat(this.products[i].price)
}
}
})
.catch(function (error) {
console.log("Error 2");
console.log(error)
})
},
removeFromCart(product_id) {
console.log('Product_id:', product_id);
var data = { 'product_id': product_id };
fetch('/api/remove_from_cart/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token }}'
},
credentials: 'same-origin',
body: JSON.stringify(data)
})
.then((response) => {
console.log(response);
this.products = this.products.filter(product => product.id !== product_id)
})
.catch(function (error) {
console.log("Error 3");
console.log(error)
})
}
}
});
</script>
{% endblock %}
views.py
import json
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from apps.cart.cart import Cart
from .models import Product
def api_add_to_cart(request):
data = json.loads(request.body)
jsonresponse = {'success': True}
print (request.body)
product_id = data['product_id'] #This is when the error is triggered
update = data['update']
quantity = data['quantity']
cart = Cart(request)
product = get_object_or_404(Product, pk=product_id)
if not update:
cart.add(product=product, quantity=1, update_quantity=False)
else:
cart.add(product=product, quantity=quantity, update_quantity=True)
return JsonResponse(jsonresponse)
def api_remove_from_cart(request):
print(request.POST)
data = json.loads(request.body)
print(data)
jsonresponse = {'success': True}
product_id = str(data['product_id']) # Error also triggered here but if we can figure out issue above solution should apply here as well
cart = Cart(request)
cart.remove(product_id)
return JsonResponse(jsonresponse)
from django.shortcuts import render, redirect
from .cart import Cart
def cart_detail(request):
cart = Cart(request)
productsstring = ''
for item in cart:
product = item['product']
b = "{'id': '%s', 'title': '%s', 'price': '%s', 'quantity': '%s', 'total_price': '%s'}," % (product.id, product.title, product.price, item['quantity'], item['total_price'])
productsstring = productsstring + b
context = {
'cart': cart,
'productsstring': [productsstring.rstrip(',')]
}
return render(request, 'cart.html', context)