Home > database >  I got decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
I got decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]

Time:05-01

views.py


@api_view(["POST", "GET"])
@permission_classes([IsAuthenticated])
def add_order(request, pk):
    print(request.user)
    customer = md.Customer.objects.get(pk=pk)
    if request.method == "POST":
        description = request.data['description']
        price = request.data['price']
        order = md.Order.objects.create(customer=customer,
                                        date_created=zt.now(),
                                        description=description,
                                        price=float(price),
                                        customer_total_when_created=customer.total_owe[0]
                                        )
        try:
            is_paid = request.data['is_paid']
            if is_paid == "on":
                who_paid = request.data['who_paid']
                payment_method = request.data['payment_method']
                who_took_money = request.user
                if who_paid == customer.name:
                    order.who_paid = customer
                elif who_paid == customer.parent:
                    order.who_paid = customer.parent
                order.payment_method = payment_method
                order.who_took_money = who_took_money
                order.date_paid = zt.now()
            customer.total = customer.total_owe
            customer.save()
            order.save()

        
        except:
            print("no payment succeed")
        order_api = OrderSerializer(order)
        return Response(order_api.data)
    customer_api = CustomerSerializer(customer)
    parent_api = CustomerSerializer(customer.parent)
    context = {
        "customer": customer_api.data,
        "parent":parent_api.data,
        "sample": [
            {"description": "secreal", "price": "12.21", "is_paid": "on", "who_paid": "azra", "payment_method": "CARD"}
        ]
    }
    return Response(context)

models.py

class Order(models.Model):
    payment_method_list = [("CASH","CASH"),("CARD","CARD")]
    customer = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True,blank=True,)
    who_paid = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True,blank=True, related_name='%(class)s_requests_created')
    who_took_money = models.ForeignKey(User,on_delete=models.CASCADE,null=True,blank=True, related_name='who_took_money')


    payment_method = models.CharField(choices=payment_method_list,max_length=4,default="CASH",blank=True,null=True)
    date_paid = models.DateTimeField(blank=True,null=True)
    date_created = models.DateTimeField(blank=True, null=True)
    date_modified = models.DateTimeField(blank=True, null=True, auto_now=True)

    is_paid = models.BooleanField(default=False, blank=True,null=True)
    customer_total_when_paid = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True)
    customer_total_when_created = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True)
    description = models.TextField(blank=True,null=True)
    price = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True)


    def __str__(self):
        return self.description[0:12]



from django.db.models.signals import post_save
def update_total_owe_created_order(sender,instance,created,**kwargs):
    
    if created:
        order = instance
        customer = order.customer
        customer.total = customer.total_owe[0]
        customer.save()

post_save.connect(update_total_owe_created_order,sender=Order)

def update_total_owe_updated_order(sender,instance,created,**kwargs):
    if created==False:
        order = instance
        customer = order.customer
        customer.total = customer.total_owe[0]
        customer.save()
post_save.connect(update_total_owe_updated_order,sender=Order)

postman post request

I have an app that you send your order to and it adds to database. It only allows authenticated user to add order; so it shows who added that order. I can get the request.user with JWT authentication but can't save the model. When I send an API post request, I get that error. I could get the user with token but it gives me that error. I don't know why. I am using postman. I didn't get it normally but when I use postman it doesn't work.

    ret = super().data
  File "C:\Users\homet\Desktop\pharmacy\venv\lib\site-packages\rest_framework\serializers.py", line 253, in data
    self._data = self.to_representation(self.instance)
  File "C:\Users\homet\Desktop\pharmacy\venv\lib\site-packages\rest_framework\serializers.py", line 522, in to_representation
    ret[field.field_name] = field.to_representation(attribute)
  File "C:\Users\homet\Desktop\pharmacy\venv\lib\site-packages\rest_framework\serializers.py", line 522, in to_representation
    ret[field.field_name] = field.to_representation(attribute)
  File "C:\Users\homet\Desktop\pharmacy\venv\lib\site-packages\rest_framework\fields.py", line 1127, in to_representation
    value = decimal.Decimal(str(value).strip())
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]

CodePudding user response:

The price in your Order model is a decimal field but you are casting the price from post request to float while creating the Order object.

price = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True)

The price should be a Decimal object instead of float.

order = md.Order.objects.create(customer=customer,
                                        date_created=zt.now(),
                                        description=description,
                                        price=Decimal(price),
                                        customer_total_when_created=customer.total_owe[0]
                                        )

customer_total_when_created should also be a Decimal instance but you haven't posted the Customer model which has total_owe.

  • Related