How to use decimal quantity for Django-Shop CartItems

76 views Asked by At

Hi I'm trying to edit the demo of Django-Shop.

I installed the version 1.2.4 of Django-Shop and Django 3.0.14 using Python 3.7.5.

In my case, I want to sell Products also by weight. As said in the documentation, I have to rewrite the CartItem.

from django.db import models
from django.utils.translation import ugettext_lazy as _

from shop.models import cart


class CartItem(cart.BaseCartItem):
    quantity = models.DecimalField(_("Cart item quantity"), decimal_places=3, max_digits=3)

I imported this CartItem in my models.py. After that, I had to rewrite the quantity in the class OrderItem as well.

class OrderItem(BaseOrderItem):
    quantity = models.DecimalField(_("Ordered quantity"), decimal_places=3, max_digits=3)
    # quantity = models.PositiveIntegerField(_("Ordered quantity"))
    canceled = models.BooleanField(_("Item canceled "), default=False)

    def populate_from_cart_item(self, cart_item, request):
        super().populate_from_cart_item(cart_item, request)
        # the product's unit_price must be fetched from the product's variant
        try:
            variant = cart_item.product.get_product_variant(
                product_code=cart_item.product_code)
            self._unit_price = Decimal(variant.unit_price)
        except (KeyError, ObjectDoesNotExist) as e:
            raise CartItem.DoesNotExist(e)

Now I can run the server without problems, but I can't add something to my cart.

I don't know what to do...

1

There are 1 answers

1
Practer On

If the models.DecimalField are exchanged for models.FloatField, the products can be added to the shopping cart as expected. Apparently the documentation in which the DecimalField is explicitly mentioned is wrong.