Django Ajax постинг дублирующихся значений в представление
Я пытаюсь отправить значение html элемента (id элемента) в представление, чтобы оно могло добавить элемент в корзину, однако оно всегда отправляет значение последнего элемента, выведенного django {% for %}, даже если источник html говорит, что значения разные
вот мой html
<div class="container">
<div class="row row-cols-2 row-cols-md-3" data-masonry='{"percentPosition": true }'>
{% for product in products %}
<div class="col mb-4">
<div class="card h-100">
{% if product.image %}
<img src="{{ product.image.url }}" class="card-img-top" alt="{{ product.description }}">
{% endif %}
<div class="card-body">
<h5 class="card-title">{{ product.name }}</h5>
<p class="card-text">{{ product.description|slice:":100" }}...</p>
<p class="card-text">${{ product.price }}</p>
<p>
<a class="btn btn-dark gap-2 mb-1" href="{{ product.get_absolute_url }}">View Item</a>
<button class="btn btn-outline-success" id="add-to-cart" value="{{ product.id }}">Add to Cart</button>
</p>
{% if product.in_stock == False %}
<p>
Item is currently out of stock
</p>
{% endif %}
</div>
</div>
</div>
{% endfor %}
</div>
</div>
Здесь Ajax
$(document).on('click', '#add-to-cart', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url "add_to_cart" %}',
data: {
productid: $('#add-to-cart').val(),
csrfmiddlewaretoken: '{{ csrf_token }}',
action: 'post'
},
success: function(json){
},
error: function(xhr, errmsg, err) {
}
});
})
Вот мое мнение
def CartAddView(request):
cart = Cart(request)
if request.POST.get('action') == 'post':
product_id = int(request.POST.get('productid'))
product = get_object_or_404(Product, id=product_id)
cart.add(product=product)
response =JsonResponse({
'price': product.price,
'id': product.id, (here the id returned is always the id of the last element printed by the loop)
})
return response
я пытался сделать страницу с подробным описанием товара и когда я вызываю ajax, она работает отлично
когда форма отправляется и просматривается ответ, страница перезагружается и снова вызывает POST, я исправил это с помощью
- создайте новый маршрут, но отобразите ту же страницу (если вы хотите отобразить ту же страницу)
- изменить возврат API
return HttpResponseRedirect('url-new')
пример:
def CartAddView(request):
cart = Cart(request)
if request.POST.get('action') == 'post':
product_id = int(request.POST.get('productid'))
product = get_object_or_404(Product, id=product_id)
cart.add(product=product)
response =JsonResponse({
'price': product.price,
'id': product.id, (here the id returned is always the id of the last element printed by the loop)
})
return HttpResponseRedirect('url')