我的购物车中出现错误[<类'十进制.转换语法'>],我该如何解决这个问题?



在向购物车中添加商品时,在/cart/处出现InvalidOperation错误[& lt;类decimal.ConversionSyntax的祝辞]。

我代码:

购物车. . py ...............................

from decimal import Decimal
from django.conf import settings
from TeaYardApp.models import Products

class Cart(object):
def __init__(self, request):
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
def __iter__(self):
product_ids = self.cart.keys()
# получаем товары и добавляем их в корзину
product = Products.objects.filter(id__in=product_ids)
cart = self.cart.copy()
for product in product:
cart[str(product.id)]['product'] = product
for item in cart.values():
item['price'] = Decimal(item['price'])
item['total_price'] = item['price'] * item['quantity']
yield item
def __len__(self):
return sum(item['quantity'] for item in self.cart.values())
def add(self, product, quantity=1, update_quantity=False):
product_id = str(product.id)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': 0,
'price': str(product.price)}
if update_quantity:
self.cart[product_id]['quantity'] = quantity
else:
self.cart[product_id]['quantity'] += quantity
self.save()
def save(self):
self.session.modified = True
def remove(self, product):
product_id = str(product.id)
if product_id in self.cart:
del self.cart[product_id]
self.save()
def get_total_price(self):
return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())
def clear(self):
del self.session[settings.CART_SESSION_ID]
self.save()

形式将商品添加到购物车,forms.py ..................................

from django import forms
PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(25, 200+1, 25)]

class CartAddProductForm(forms.Form):
quantity = forms.TypedChoiceField(
choices=PRODUCT_QUANTITY_CHOICES,
coerce=int)
update = forms.BooleanField(required=False,
initial=False,
widget=forms.HiddenInput)

我不知道修复此错误,请帮助 . ....................................

回溯:

Traceback (most recent call last):
File "C:my_projectsTeaYardvenvlibsite-packagesdjangocorehandlersexception.py"
, line 55, in inner
response = get_response(request)
File "C:my_projectsTeaYardvenvlibsite-packagesdjangocorehandlersbase.py", lin
e 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:my_projectsTeaYardAppcartviews.py", line 30, in cart_detail
for item in cart:
File "C:my_projectsTeaYardAppcartcart.py", line 28, in __iter__
item['price'] = Decimal(item['price'])
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]

detail.html

{% extends "base.html" %}
{% load static %}
{% block title %}
Корзина покупок
{% endblock %}
{% block content %}
<h1>Корзина покупок</h1>
<table class="cart">
<thead>
<tr>
<th>Картинка</th>
<th>Товар</th>
<th>Обновить кол-во</th>
<th>Удалить</th>
<th>Кол-во</th>
<th>Цена за шт</th>
<th>Общая стоимость</th>
</tr>
</thead>
<tbody>
{% for item in cart %}
{% with product=item.product %}
<tr>
<td>
<a href="{{ product.get_absolute_url }}">
<img src="{% if product.image %}{{ product.image.url }}{% else %}{% static 'PDF/no_image.png' %}{% endif %}">
</a>
</td>
<td>{{ product.name }}</td>
<td>
<form action="{% url 'cart:cart_add' product.id %}" method="post">
{{ item.update_quantity_form.quantity }}
{{ item.update_quantity_form.update }}
<input type="submit" value="Обновить">
{% csrf_token %}
</form>
</td>
<td><a href="{% url 'cart:cart_remove' product.id %}">Удалить</a></td>
<td>
{{ item.quantity }}
</td>
<td class="num">{{ item.price }}</td>
<td class="num">{{ item.total_price }}</td>
</tr>
{% endwith %}
{% endfor %}
<tr class="total">
<td>Всего</td>
<td colspan="4"></td>
<td class="num">{{ cart.get_total_price }}</td>
</tr>
</tbody>
</table>
<p class="text-right">
<a href="{% url 'home' %}" class="button light">В магазин</a>
<a href="#" class="button">Оформить заказ</a>
</p>
{% endblock %}
C:my_projectsTeaYardAppcartviews.py, line 30, in cart_detail
for item in cart: …
Local vars
C:my_projectsTeaYardAppcartcart.py, line 35, in __iter__
raise ValueError('price must be numeric value') …
Local vars
Variable    Value
cart    
{'1': {'price': '7 руб/кг',
'product': <Products: Молочный улун>,
'quantity': 325},
'2': {'price': '7', 'quantity': 25}}
item    
{'price': '7 руб/кг', 'product': <Products: Молочный улун>, 'quantity': 325}
price   
'7 руб/кг'
product 
<Products: Молочный улун>
product_ids 
dict_keys(['1', '2'])
self    
<cart.cart.Cart object at 0x000001B47BA33FA0>

根据回溯错误发生在这一行:

item['price'] = Decimal(item['price'])

这是因为item['price']不是数字。例如,当item['price']的值为''abc时,可能发生此错误。

如果你使用Django Rest框架,那么序列化器是验证输入数据的最佳方式。

如果你只是想简单地避免错误,最简单的方法是每次检查item['price']的值:

# convert to string first (to be able call isnumeric method)
price = str(item['price'])
# check if price string is numeric
if price.isnumeric()
price = Decimal(price)
else:
# handle bad value (raise error or whatever depending on your logic)
raise ValueError('price must be numeric value')

您传递给Decimal函数的值不正确。如果你给即空字符串("")给该函数,那么你会得到这样的错误。你应该检查你在那里放了什么值。

您可以在Cart模型的get_total_price函数中尝试此操作:

def get_total_price(self):
price = item['price'] if item['price'] else 0
return sum(Decimal(price) * item['quantity'] for item in self.cart.values())

如果问题与'quantity'相同,则用相同的方法解决