def清除方法中的十进制计数错误?

时间:2009-06-07 17:42:12

标签: django django-forms

我正在尝试在验证后的def清理方法中进行一些简单的计算(基本上随意吐出检索到的英国产品价格的欧元转换)。我一直得到一个TypeError。

完整错误读取:

无法转换{'product':,'invoice':,'order_discount':十进制(“0.00”),'order_price':{...},'order_adjust':无,'order_value':无,' DELETE':False,'id':92,'quantity':8}到Decimal

所以我猜django正在将整个cleaning_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方法中执行十进制转换是否应该成为问题?

由于

1 个答案:

答案 0 :(得分:0)

我将假设你在粘贴时出现了缩进错误,来自if data['invoice_type'] == 1:的行应该实际缩进一级 - 否则,正如Alex所说,代码永远不会达到十进制转换。

此代码还有其他多个问题,但最大的问题是最后一行返回整个cleaning_data字典,而不是此特定字段的值 - 我怀疑这是您看到的错误的原因。

除此之外,通过将calc乘以cost_price_gross计算exchange会出现很大的错误。这里exchange是EuroExchangeRate的一个实例,而不是一个数字,所以这个计算不起作用。