Django and HTMX - AttributeError: 'int' object has no attribute 'get'

Django and HTMX - AttributeError: 'int' object has no attribute 'get'

我正在尝试使这个 POST 调用与 Django 一起工作:

<span id="quantity-in-cart">{{item.quantity_in_cart}}</span>
<button class="btn btn-success btn-sm" hx-post="/cart/add/1/" hx-target="#quantity-in-cart" hx-swap="outerHTML">+</button>

但是,当我单击执行 POST 调用的按钮时,出现此错误:

Internal Server Error: /cart/add/4/
Traceback (most recent call last):
  File "/home/neisor/.local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/neisor/.local/lib/python3.9/site-packages/django/utils/deprecation.py", line 119, in __call__
    response = self.process_response(request, response)
  File "/home/neisor/.local/lib/python3.9/site-packages/django/middleware/clickjacking.py", line 26, in process_response
    if response.get('X-Frame-Options') is not None:
AttributeError: 'int' object has no attribute 'get'
[22/Mar/2022 12:47:01] "POST /cart/add/4/ HTTP/1.1" 500 66757

我的模板中 <body> 标签末尾也有这个:

<script>
 document.body.addEventListener('htmx:configRequest', (event) => {
    event.detail.headers['X-CSRFToken'] = '{{ csrf_token }}';
 })
</script>

有什么解决办法吗?

谢谢

编辑:

对应cart/add/<int:product_id>/的视图是这样的:

def add_to_cart(request, product_id):
    """
    Cart structure:
    {
        "items": {
            "product_id1": quantity_in_cart,
            "product_id2": quantity_in_cart,
            ...
        },
        "total_value_in_cart": 0 # in EURO
    }    
    """
    try:
        product_id_as_int = int(product_id)
    except ValueError:
        messages.error(request, 'Produkt, ktorý ste chceli pridať do košíka, nie je správny.')
        return redirect(request.META.get('HTTP_REFERER', index))
    # Get quantity value from the request (from the form in the template)
    quantity = request.POST.get('quantity')
    return_only_quantity = False
    if not quantity: # If there is no quantity provided, do not redirect and return only amount in cart of the product
        return_only_quantity = True
        quantity = 1
    try:
        quantity_as_int = int(quantity)
    except ValueError:
        messages.error(request, 'Quantity to add to cart is not correct.')
        return redirect(request.META.get('HTTP_REFERER', index))
    check_if_cart_exists_in_sessions(request)
    cart = request.session['cart']
    cart_items = cart['items']
    try:
        product = Product.objects.get(pk=product_id_as_int)
    except Product.DoesNotExist:
        messages.error(request, 'Product does not exist.')
        return redirect(request.META.get('HTTP_REFERER', index))
    product_id_as_string = str(product_id)
    # Check if such a product is already in the cart_items
    if cart_items.get(product_id_as_string):
        cart_items[product_id_as_string] += quantity_as_int
        request.session.modified = True # Save the modification
    else: # If such a product does not yet exist in the cart_items
        cart_items[product_id_as_string] = quantity_as_int
    # Count total_value_in_cart
    count_total_value_in_cart(request)
    if return_only_quantity:
        return cart_items[product_id_as_string]
    else:
        messages.success(request, f'Inserted in cart.')
        return redirect(request.META.get('HTTP_REFERER', index))

此视图用于将商品添加到购物车。它也从应用程序的其他部分发送一个带有数量的表格。但是从这个特定的视图中,我只想点击一个按钮,向这个视图发送一个 POST 请求,在 return 中,只需将数量 1 添加到所提供的 product_id 的购物车中.

问题出在这一行:

return cart_items[product_id_as_string]

Django 需要 HTTP 响应。如果您只想显示数字,请将其替换为:

return HttpResponse(cart_items[product_id_as_string])