【发布时间】:2009-06-07 17:42:12
【问题描述】:
我正在尝试在验证后的 def clean 方法中进行一些简单的计算(基本上是即时吐出检索到的英国产品价格的欧元转换)。我不断收到 TypeError。
完整的错误读取:
无法转换 {'product': , 'invoice': , 'order_discount': Decimal("0.00"), 'order_price': {...}, 'order_adjust': None, 'order_value': None, ' DELETE': False, 'id': 92, 'quantity': 8} 到十进制
所以我猜 django 正在将整个 clean_data 表单传递给 Decimal 方法。不确定我哪里出错了 - 我正在使用的代码是:
def clean_order_price(self):
cleaned_data = self.cleaned_data
data = self.data
order_price = cleaned_data.get("order_price")
if not order_price:
try:
existing_price = ProductCostPrice.objects.get(supplier=data['supplier'], product_id=cleaned_data['product'], is_latest=True)
except ProductCostPrice.DoesNotExist:
existing_price = None
if not existing_price:
raise forms.ValidationError('No match found, please enter new price')
else:
if data['invoice_type'] == 1:
return existing_price.cost_price_gross
elif data['invoice_type'] == 2:
exchange = EuroExchangeRate.objects.latest('exchange_date')
calc = exchange.exchange_rate * float(existing_price.cost_price_gross)
calc = Decimal(str(calc))
return calc
return cleaned_data
如果发票是类型 2(欧元发票),则系统应获取最新汇率并将其应用于匹配的英镑价格,以获得欧元结果。
在 def clean 方法中执行十进制转换应该是一个问题吗?
谢谢
【问题讨论】:
-
我不明白您发布的代码是如何到达十进制的:它在 if/elif 之前无条件地引发异常。请检查并更正缩进?
-
另外,一旦你进行了编辑:为什么你两次从cleaned_data获得“order_price”,一次用get分配给你然后忽略的变量,一次用[]索引?为什么在某些情况下返回 Decimal 而在其他情况下返回 dict ?这是相当混乱的代码!
标签: django django-forms