Как поместить все элементы моей корзины в XML Django

Кто-нибудь знает, почему возвращается только 1 товар? В моей корзине 2 товара. Вот переменная "item_dict":

 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)

В моем HttpResponse(item_dict) он возвращает мне только 1 элемент enter image description here

<<<0><><0>Моя цель состоит в том, чтобы иметь возможность возвращать все товары в моей корзине в моем XML

enter image description here

Я не знаю, что я делаю неправильно.

Наиболее вероятная причина в том, что оператор return находится внутри цикла for, поэтому цикл всегда будет возвращаться на первой итерации. Скорее всего, вам нужно что-то вроде:

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)

Хотя в этом примере не рассматривается сложение total и quantity, обратите внимание, что оператор return находится вне цикла for.

Вернуться на верх