Home > Software design >  Error: decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>] in Django
Error: decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>] in Django

Time:09-30

Django View:

@api_view(['PUT'])
@permission_classes([IsAdminUser])
def updateProduct(request, pk):
    data = request.data

    product = Product.objects.get(_id=pk)
    product.name = data['name'],
    product.price = data['price'],
    product.category = data['category']
    product.description = data['description']
    product.countInStock = data['countInStock']
    print(data)

    serializer = ProductSerializer(product, many =False)

    return (Response(serializer.data))

Models.py:

class Product(models.Model):
    user = models.ForeignKey(User, on_delete = models.SET_NULL, null=True)
    name = models.CharField(max_length = 200, null= True, blank= True)
    image = models.ImageField(default="/place.jpg",null= True, blank= True)
    netWeight = models.CharField(max_length = 200, null= True, blank= True)
    category = models.CharField(max_length = 200, null= True, blank= True)
    description = models.TextField(null = True, blank= True)
    rating = models.DecimalField(max_digits = 7, decimal_places = 2,null= True, blank= True)
    price = models.DecimalField(max_digits = 7, decimal_places = 2,null= True, blank= True)
    numReviews = models.IntegerField(null= True, blank= True, default=0)
    countInStock = models.IntegerField(null= True, blank= True, default=0)
    createdAt = models.DateTimeField(auto_now_add=True)
    _id = models.AutoField(primary_key=True, editable=False)

Product Action.js (React):

export const listProductUpdate = (product) => async (dispatch, getState) => {
  try {
      dispatch({
          type: PRODUCT_UPDATE_REQUEST
      })

      const {
          userLogin: { userInfo },
      } = getState()

      const config = {
          headers: {
              'Content-type': 'application/json',
              Authorization: `Bearer ${userInfo.token}`
          }
      }

      const { data } = await axios.put(
          `/api/products/update/${product._id}/`,
          product,
          config
      )

      dispatch({
          type: PRODUCT_UPDATE_SUCCESS,
          payload: data
      })
      dispatch({
          type: PRODUCT_DETAILS_SUCCESS,
          payload: data
      })
  } catch (error) {
      dispatch({
          type: PRODUCT_UPDATE_FAIL,
          payload: error.response && error.response.data.detail
              ? error.response.data.detail
              : error.message,
      })
  }
}

I have used React as frontend and Django as backend. The data sent from the form is being used as string. How to convert the 'Price' and 'CountInStock' to DecimalField value? While triggering action from the frontend, the product is not getting updated and the above-mentioned error is being displayed. Can anyone please help me to solve this

CodePudding user response:

You can register some Django decimal value by using python deimal.Decimal object. An convert a string to int with int('string_number') like this :

from decimal import Decimal

def updateProduct(request, pk):
    # Some code here
    product.price = Decimal(data['price']),
    product.countInStock = int(data['countInStock'])
    # Some stuff here

NB : Here we assume that all the verification for Decimal and int object are checked in the frontend before. It means that data['price'] must be valid decimal number once converted and data['countInStock'] is a valid int number when converted too. The Decimal doc

  • Related