Home > Enterprise >  How to put all my cart items in an XML Django
How to put all my cart items in an XML Django

Time:12-09

Does anyone know why it's returning only 1 item? There are 2 items in my cart. Here is the "item_dict" variable:

 cart_items = CartItem.objects.filter(user=current_user)
 for cart_item in cart_items:
        total  = (cart_item.product.price * cart_item.quantity)
        quantity  = cart_item.quantity

        item_dict = f"""
            <item>
                <id>{cart_item.product.id}</id>\r\n
                <description>{cart_item.product.name}</description>\r\n
                <quantity>{cart_item.quantity}</quantity>\r\n
                <amount>{cart_item.product.price}</amount>\r\n
            </item>
            """
        return HttpResponse(item_dict)

In my HttpResponse(item_dict) it is returning me only 1 item enter image description here

Meu objetivo é poder devolver todos os itens do meu carrinho no meu XML enter image description here

I don't know what I'm doing wrong.

CodePudding user response:

Most likely reason is the return statement is inside the for loop, so the loop will always return on the first iteration. You probably need something more like:

returnable_string = ''

for cart_item in cart_items:
    returnable_string  = f"""
        <item>
            <id>{cart_item.product.id}</id>\r\n
            <description>{cart_item.product.name}</description>\r\n
            <quantity>{cart_item.quantity}</quantity>\r\n
            <amount>{cart_item.product.price}</amount>\r\n
        </item>
        """

return HttpResponse(returnable_string)

Although this example doesn't deal with adding up the total and quantity, notice that the return statement is outside the for loop.

  • Related