【问题标题】:Update Django context variable using Ajax使用 Ajax 更新 Django 上下文变量
【发布时间】:2021-03-01 12:56:09
【问题描述】:

我花了相当长的时间试图找到一个解决方案,但我对 Django 还很陌生,我似乎无法解决这个问题。

在我的详细视图中,我传递了我想在模板中显示的产品(产品)以及产品的第一个产品类型(pid)。

当通过 detail.html 中的下拉框选择新产品类型时,我需要在不重新加载页面的情况下更新产品类型上下文变量,因此 我可以将其作为参数发送到 cart_add 视图网址。

我想我可以使用 Ajax 来做到这一点。我可以显示所选产品类型的值,但我不知道如何将上下文变量更新为这个新值。

views.py

def product_detail(request, id, slug):
    product = get_object_or_404(Product, id=id, slug=slug)
    product_types = ProductType.objects.filter(product=product, available=True)
    pid = product_types[0]
    mylist = []
    for product_type in product_types:
        mylist.append(dict((x.base, x.value) for x in ProductAttribute.objects.filter(product_type=product_type)))
    category = Category.objects.get(id=product.category.id)
    parent_category = category.parent_category
    cart_product_form = CartAddProductForm()
    return render(
        request,
        'shop/product/detail.html',
        {'parent_category':parent_category, 'category':category, 'product': product, 'cart_product_form': cart_product_form, 'product_types': product_types, 'mylist': mylist, 'pid':pid}

def load_product_type(request):
    product_type_id = request.GET.get('product_type_pk')
    product_type = ProductType.objects.get(id=product_type_id)
    return render(request, 'shop/product/product-type.html', {'product_type': product_type})

product-type.html

{{product_type.id}}

detail.html

<select name="product_type" id="product_type" data-product_type-url="{% url 'shop:ajax_load_product_type' %}" required class="form-control">
                {% for product_type in product_types %}
                    <option value="{{product_type.id}}">{{product_type.reference}}</option>
                {% endfor %}
</select>
        
<p class="product-id" id="product-id"></p>  
        
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
    $("#product_type").change(function () {
        var url = $("#product_type").attr("data-product_type-url");  
        var product_type_pk = $(this).val();  
        
        $.ajax({                       
            url: url,                    
            data: {
                'product_type_pk': product_type_pk,       
                 },
                success: function (data) {
                    // instead of showing it in the template, I want something like
                    // pid = data
                    $("#product-id").html(data);  
                 }
            });
        });
        </script>

        // This is where I want to assign to pid the new selected product type
        <form action="{% url 'cart:cart_add' pid.id  %}" method="post">
            {{ cart_product_form }}
            {% csrf_token %}
            <input type="submit" value="Add to cart">
        </form>

感谢您的帮助

【问题讨论】:

  • 您不能从客户端替换上下文变量,因为它们对于客户端甚至不存在。客户端不知道 html 是如何呈现的(所有这些都是在服务器端完成的),它确实不应该。
  • 知道@AbdulAzizBarkat 如何在服务器端进行操作吗?
  • 你到底想做什么?改变表单的动作属性?只需在响应中发送表单的 url 并使用 javascript 进行设置。
  • 我想把pid改成选中的product_type.id
  • 你想改变表单的action属性,是吗?

标签: django ajax


【解决方案1】:

我假设您只是想更改表单的 action 属性。首先在您的表单上设置一个 id:

<form action="{% url 'cart:cart_add' pid.id  %}" method="post" id="my-form">

现在在你的模板product-type.html 中写:

{% url 'cart:cart_add' product_type.id  %}

现在在你的 javascript 中的成功函数中(对于 ajax):

$("#my-form").attr("action", data);

注意:可能发送JsonResponse 将更具指示性,然后通过在模板中呈现数据来发送数据

【讨论】:

  • 现在我回过头来看它,也许你甚至不需要 ajax。 product_type_pk不是已经是你需要的pk了吗?您可以在 javascript 中构建新的 url。
  • 是的。如何使用 product_type_pk 做到这一点?谢谢你的帮助
  • @SofiaLazrak 实际上你甚至不需要这样做。您可以简单地将选择标签部分放在表单中,然后发布到一个 url,而不是根据所选选项更改 url。
  • 类似:code
    {{ car​​t_product_form }} ...
    code
  • @SofiaLazrak 而不是这样做只是将字段直接添加到您的表单类中......
猜你喜欢
  • 2016-05-11
  • 2012-04-16
  • 2018-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-15
相关资源
最近更新 更多