These are chat archives for django/django

30th
Jun 2018
Himanshu Shankar
@iamhssingh
Jun 30 2018 02:38
Yeah @johndiego
Curtis Maloney
@funkybob
Jun 30 2018 02:41
@johndiego a tip.. don't ask if anyone can help... when you haven't provided any details :)
just explain the problem... it's possible someone who hasn't used it can still help
Himanshu Shankar
@iamhssingh
Jun 30 2018 03:41
True @funkybob
MilanRgm
@MilanRgm
Jun 30 2018 04:07
Why my serializer is not valid? I keep getting serializer error
class Cart(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)
    subtotal = models.DecimalField(max_digits=50, decimal_places=2, default=0.00)


class CartItem(models.Model):
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
    item = models.ForeignKey(Variation, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField(default=1)
    line_item_total = models.DecimalField(max_digits=10, decimal_places=2)


class CartSerializer(serializers.ModelSerializer):
    item = VariationSerializer(many=True, read_only=True)

    class Meta:
        model = Cart
        fields = ('item', 'user', 'timestamp', 'updated', 'subtotal', 'total', 'active',)


class CartItemSerializer(serializers.ModelSerializer):

    class Meta:
        model = CartItem
        fields = '__all__'


class CartAPI(APIView):
    serializer_class = serializers.CartItemSerializer

    def get(self, request, format=None):
        reply = {}
        try:
            carts = CartItem.objects.all()
            reply['data'] = self.serializer_class(carts, many=True).data
        except CartItem.DoesNotExist:
            reply['data'] = []
        return Response(reply, status.HTTP_200_OK)

    def post(self, request, format=None):
        '''
        {
          "product": 3,
           "quantity": 4
        }
        '''
        reply = {}
        cart = Cart(request)
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            pdb.set_trace()
            data = serializer.data
            product_instance = data.get('product')
            quantity = data.get('quantity')
            cart_data = cart.add(product_instance, quantity)
            reply['data'] = cart_data
            return Response(reply, status.HTTP_200_OK)
        return Response(serializer.errors)
Curtis Maloney
@funkybob
Jun 30 2018 04:09
what error?
MilanRgm
@MilanRgm
Jun 30 2018 04:10
request {'product': 3, 'quantity': 4} this is the request.data
deubbuger is not reached to serializer.is_valid() block because I am getting error like cart: ["this field is required"] as in above screenshot
@funkybob is my screenshot of error shown? just confirming if it is shown or not.
Curtis Maloney
@funkybob
Jun 30 2018 04:15
yeah, I see it now
since the cart to add it to is implied (I assume) you should probably omit cart from the serialiser for updates [is that possible in DRF?]
in nap you'd mark that field as readonly
MilanRgm
@MilanRgm
Jun 30 2018 04:18
you mean to say omit cart from the CartItemSerializer?
Curtis Maloney
@funkybob
Jun 30 2018 04:19
yes
MilanRgm
@MilanRgm
Jun 30 2018 04:21
i will give it a try
I get error of
 "item": [
        "This field is required."
    ]
Curtis Maloney
@funkybob
Jun 30 2018 04:24
it's only doing what you told it... you said it needs an item, it requires an item
MilanRgm
@MilanRgm
Jun 30 2018 04:27
i had to do partial=True this solved the above issue but getting another issue now lol
MilanRgm
@MilanRgm
Jun 30 2018 04:40
print ('request', request.data) it gives me both product and quantity but data = serializer.datagives only quantity. There is no product
MilanRgm
@MilanRgm
Jun 30 2018 08:03
Can anyone help me to look at my carts.py file, please? I messed my code and I am trying to figure out but its not going in the proper flow.
import pdb
import datetime
from django.http import Http404

from carts.models import Cart, CartItem
from products.models import Variation

CART_ID = 'cart-id'


class Basket(object):

    def __init__(self, request):
        """
        Initialize the cart
        """
        self.session = request.session
        self.current_user = request.user
        # get the current session from request.session.get(CART_ID)
        cart = self.session.get(CART_ID)
        if not cart: # cart is not present in the session
            # save an empty cart in the session
            # but we expect our cart dictionary to use product ids as keys
            # and a dictionary with quantity and price as value for each key
            # by that we can gurantee same product is not added twice
            cart = self.session[CART_ID] = {}
        else:
            try:
                cart = Cart.objects.get(id=cart)
            except Cart.DoesNotExist:
                cart = self.session[CART_ID] = {}
        self.cart = cart


    def __iter__(self):
        """
        Iterate over the items in the cart and get the products from the database
        """
        product_ids = self.cart.keys()
        # get the product objects and add them to the cart
        products = Variation.objects.filter(id__in=product_ids)
        for product in products:
            self.cart[str(product.id)]['product'] = product
        for item in self.cart.values():
            item['price'] = Decimal(item['price'])
            item['total_price'] = item['price'] * item['quantity']
            yield item


    def __len__(self):
        """
        Count all the items in the cart
        """
        return sum(item['quantity'] for item in self.cart.values())


    def get_total_price(self):
        return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())


    def clear(self):
        # empty cart
        self.session[CART_ID] = {}
        self.session.modified = True


    def new(self, request):
        cart = Cart(user=request.user, timestamp=datetime.datetime.now())
        cart.save()
        request.session[CART_ID] = cart.id
        return cart


    def add(self, product_id, quantity=1, update_quantity=False):
        """
        Add a product to the cart or update its quantity for True
        or the new quantity needs to be added to the existing quantity
        if it is False. We use the product id as a key and convert it to string
        because django uses JSON to serialize session data.
        """
        try:
            product = Variation.objects.get(id=product_id)
        except Variation.DoesNotExist:
            raise Http404
        cart_instance = Cart.objects.filter(id=self.cart[product_id].get('cart_id', None))
        if product_id not in self.cart and not cart_instance.count() == 1:
            # cart_item = CartItem.objects.create()
            print ('##############################################')
            cart_object = self.new(self.request)
            print ('cart_object', cart_object)
            self.cart[product_id] = {
                "cart_id": cart_object.id
            }
        if update_quantity:
            print ('##############################################')
            cart_item = CartItem.objects.get(cart=cart_object)
            print ("cart_item", cart_item)
            cart_item.quantity += quantity
            self.cart[product_id]['quantity'] += quantity
        else:
            print("#################update QUANTITY######################")
            cart_instance = Cart.objects.filter(id=product_id)
            cart_object = cart_instance.first()
            print ("cart_object", cart_object)
            if self.current_user and cart_object.user is None:
                print("##############################")
                print ('cart_object.user', cart_object.user, self.current_user)
                cart_object.user = self.current_user
                cart_object.save()
                cart_item = CartItem.objects.create(
                        cart=cart_
cart_instance = Cart.objects.filter(id=self.cart[product_id].get('cart_id', None)) i know here is the mistake but is not able to resolve it
Napoleon Arouldas
@indianwebdevil_twitter
Jun 30 2018 09:50
Can someone give the best practices of doing deployment for django based projects
Curtis Maloney
@funkybob
Jun 30 2018 09:52
you mean beyond what's in the documentation?
Napoleon Arouldas
@indianwebdevil_twitter
Jun 30 2018 09:56
yea plese
Curtis Maloney
@funkybob
Jun 30 2018 09:59
well, I have an older sort of guide .. http://musings.tinbrain.net/simple-django-deploy/
Napoleon Arouldas
@indianwebdevil_twitter
Jun 30 2018 10:03
thanks
Napoleon Arouldas
@indianwebdevil_twitter
Jun 30 2018 10:10
Quite useful, how do i do updates or releases
Curtis Maloney
@funkybob
Jun 30 2018 10:13
it's quit common to use git ... some people make their django project a python package so they can pip install it
johndiego
@johndiego
Jun 30 2018 19:38
@funkybob thanks for repply

@funkybob I'm filter with django -filter using request.POST but don't work

SEE MY ISSUE carltongibson/django-filter#933