views:

64

answers:

1

I'm attempting a few simple calculations in a def clean method following validation (basically spitting out a euro conversion of retrieved uk product price on the fly). I keep getting a TypeError.

Full error reads:

Cannot convert {'product': , 'invoice': , 'order_discount': Decimal("0.00"), 'order_price': {...}, 'order_adjust': None, 'order_value': None, 'DELETE': False, 'id': 92, 'quantity': 8} to Decimal

so I guess django is passing through the entire cleaned_data form to Decimal method. Not sure where I'm going wrong - the code I'm working with is:

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

If the invoice is of type 2 (a euro invoice) then the system should grab the latest exchange rate and apply that to the matching UK pound price pulled through to get euro result.

Should performing a decimal conversion be a problem within def clean method?

Thanks

A: 

I'm going to assume you've made an indentation error on pasting, and the lines from if data['invoice_type'] == 1: should actually be indented one level back - otherwise, as Alex says, the code will never get to the Decimal conversion.

There are multiple other problems with this code, but the biggest is that the last line returns the whole cleaned_data dictionary, rather than the value of this particular field - I suspect this is the cause of the error you are seeing.

Other than that, there is a big error where you calculate calc by multiplying cost_price_gross by exchange. Here exchange is an instance of EuroExchangeRate, rather than a number, so this calculation will not work.

Daniel Roseman