django ajax向视图发布重复值

发布于 2025-02-11 19:01:38 字数 2563 浏览 0 评论 0原文

我试图将HTML项目的值(项目的ID)发布到视图中,以便可以将项目添加到购物车中,但是它始终将Django {%for%}打印的最后一个项目的值张贴 值不同

尽管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>

是我的html ,这是

$(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时,它的工作原理非常完美

Im trying to post the value of a html item(the id of the item) to the view so it can add the item to the cart, however it always posts the value of the last item printed by the django {% for %} even though the html source says the values are different

here is my 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>

Here is the 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) {

        }
    });
})

Here is my view

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

i tried to make a product detail page and when i call the ajax it works perfectly

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

流星番茄 2025-02-18 19:01:38

当表单提交和查看返回响应页面将重新加载同一页面并再次致电帖子时,我使用

  1. 创建新路线进行修复,但呈现同一页面(如果您想呈现同一页面)
  2. 更改API返回返回httpresponserectirect( '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')

when form submit and view return response page will reload the same page and call POST again, I fixed it with

  1. create a new route but render the same page (if you want to render the same page)
  2. change API return return HttpResponseRedirect('url-new')
    examaple:
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')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文