如何将主键值从JsonResponse传递到Django中的动态url?

时间:2019-03-10 15:20:46

标签: json ajax django

我遇到了在Django中使用Ajax将主键值传递给动态url的问题。感谢您的帮助...

下面是单击按钮功能的JS代码:

$(function () {

  $(".js-create-book").click(function () {
      $.ajax({
      url: '/supplier/**<int:pk>**/new/',
      type: 'get',
      dataType: 'json',
      beforeSend: function () {
        $("#modal-book").modal("show");
      },
      success: function (data) {
        $("#modal-book .modal-content").html(data.html_form);
      }
    });
  });

});

views.py获得了new_stok()函数,如下所示:

def new_stok(request, pk):
    supplier = get_object_or_404(Supplier, pk=pk)
    form = NewStokForm()
    context = {'pk': supplier.pk, 'form': form}
    html_form = render_to_string('includes/partial_stok_create.html',
        context,
        request=request,
    )
    return JsonResponse({'html_form': html_form})

1 个答案:

答案 0 :(得分:1)

您可以使用HTML5数据属性:

   <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-catalyst_${scala.binary.version}</artifactId>
        <version>${spark.version}</version>
        <scope>compile</scope>
    </dependency>

然后在javascript中检索属性:

<button class="js-create-book" data-id="{{ supplier.pk }}">Add new</button>