Я пытаюсь заставить этот вызов 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 в это представление, которое, в свою очередь, просто добавляет количество 1 в корзину предоставленных product_id
.
@LaCharcaSoftware Только что добавил вид для /cart/add/<int:product_id>/
. Спасибо
Проблема в этой строке:
return cart_items[product_id_as_string]
Джанго ожидает ответа HTTP. Если вы хотите просто показать номер, замените его на:
return HttpResponse(cart_items[product_id_as_string])
Вы должны поделиться представлением для этого URL-адреса: /cart/add/1/ Проблема в этом представлении, потому что Django ожидает объект, но вы отправляете ему int