【问题标题】:Not able to implement delete row button in Django using ajax无法使用 ajax 在 Django 中实现删除行按钮
【发布时间】:2015-07-21 14:13:01
【问题描述】:

我正在代码中的表格中实现删除行按钮。

html如下:

    <td>
       <a href="#myModal" role="button" class="btn btn-danger delete" data-toggle="modal" id="{{item.id}}" data-name="{{item.nombre}}"><i class="icon-trash icon-white"></i>DELETE
       </a>
    </td>

这调用了一个模态窗口,代码如下:

    <div id="myModal" class="modal fade" tabindex="-1" role"dialog" aria-labeledby="myModalLabel" aria-hidden="true">
       <div class="modal-dialog">
           <div class="modal-content">
               <div class="modal-header">
                   <h3 id="myModalLabel"> Eliminar Cliente </h3>
               </div>

               <div class="modal-body">
                  <p>¿Realmente desea eliminar el producto <span id="modal_name"></span>?</p>
               </div>

               <div class="modal-footer">
                   <form method="post" id="frmEliminar">
                        {% csrf_token %}

                      <input type="hidden" id="modal_idCliente" name="cliente_id">
                      <button class="btn" data-dismiss="modal" aria-hidden="true"> Cerrar </button>
                      <button type="submit" class="btn btn-danger"> Eliminar </button> 
                   </form> 
               </div>
          </div>
    </div>

这是我的看法:

    def funcion_tabla(request,tabla_nombre):

        if request.method=="POST":

           if "cliente_id" in request.POST:
              try:
                  id_producto = request.POST['cliente_id']
                  p = Cliente.objects.filter(id=id_producto)
                  mensaje = {"status":"True","cliente_id":p.id}
                  p.delete() # Elinamos objeto de la base de datos
                  return          HttpResponse(json.dumps(mensaje),mimetype='application/json')
              except:
                  mensaje = {"status":"False"}
                  return HttpResponse(json.dumps(mensaje),mimetype='application/json')

        global resultado
        nombre = tabla_nombre.capitalize()
        if nombre == "Cliente":
           resultado = Cliente.objects.order_by('rif')
        if nombre == "Producto":
           resultado = Producto.objects.order_by('id')
        if nombre == "Cotizacion":
           resultado = Cotizacion.objects.order_by('id')
        if nombre == "Factura":
           resultado = Factura.objects.order_by('id')
        if nombre == "Prospecto":
           resultado = Prospecto.objects.order_by('id')

        return render_to_response('home/index.html', {'resultado' : resultado,'nombre_tabla':nombre})

我有这个脚本:

    var nombre_tabla = "#example"; // id
    var nombre_boton_eliminar = ".delete"; // Clase
    var nombre_formulario_modal = "#frmEliminar"; //id
    var nombre_ventana_modal = "#myModal"; // id

    $(document).on('ready',function(){
            $(nombre_boton_eliminar).on('click',function(e){
            e.preventDefault();
            var Pid = $(this).attr('id');
            var name = $(this).data('name');
            $('#modal_idCliente').val(Pid);
            $('#modal_name').text(name);

            });

            var options = {
                    success:function(response) {
                            if(response.status=="True"){
                               alert("Eliminado!");
                               var idProd = response.product_id;
                               var elementos= $(nombre_tabla+' >tbody >tr').length;

                               if(elementos==1){
                                  location.reload();
                               }else{
                                  $('#tr'+idProd).remove();
                                  $(nombre_ventana_modal).modal('hide');
                               }

                            }else{
                                alert("Hubo un error al eliminar!");
                                $(nombre_ventana_modal).modal('hide');
                            };
                    }
             };

             $(nombre_formulario_modal).ajaxForm(options);
    });

我的问题是当我尝试删除时,我收到了这条消息:

POST http://127.0.0.1 :8000/cliente/ 403(禁止)

我是 django 的新手,有什么建议吗?

【问题讨论】:

  • global resultado - 完全不相关,但您不希望在并发环境中使用全局。肯定的。
  • 谢谢,但这不是问题
  • @sbncl 我知道这“不是问题”——这就是我说它完全不相关的原因。但请相信我,这是个问题,因为您将在多线程环境中部署后立即发现
  • 感谢您的建议。

标签: jquery python ajax django django-forms


【解决方案1】:

我通过应用以下代码解决了这个问题

 @ensure_csrf_cookie 

查看并导入

from django.views.decorators.csrf import ensure_csrf_cookie

【讨论】:

    猜你喜欢
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 2017-02-06
    • 1970-01-01
    • 2016-03-18
    相关资源
    最近更新 更多