0

Estoy generando una tabla para enviarla por POST, sin embargo, al momento que envió me sale que el código CSRF es incorrecto o erróneo, ya he probado de algunas maneras y no tengo una solución correcta, adjunto el código. Views.py

class GuardarPlanificacion(TemplateView):
# Llamar al metodo para transacciones en base de datos
@transaction.atomic
def post(self, request, *args, **kwargs):
    print("Entro a guardar planificación")
    datosplanificacion = {}
    _transaccion = transaction.savepoint()
    try:
        valor = request.POST.get('datosplaning', None)
        print(valor)
        datosplanificacion = json.loads(request.POST['datosplaning'])
        print(datosplanificacion)
        fechaactual = time.strftime("%Y-%m-%d")
        print('pasa')
        for semana in datosplanificacion["semana"]:
            semanaactividad = int(semana)
        print('pasa')
        for planifica in datosplanificacion['planificacion']:
            print('entra')
            # print(planifica['actividad'])
            actividad = planifica['actividad']
            fechainicio = planifica['fechainicio']
            fechafin = planifica['fechafin']
            detalleplanificacion = Detalleplanificacionactividad(
                secuencial_actividad=Actividad.objects.get(
                    nombre=actividad),
                secuencial_planificacion=Planificacion.objects.get(
                    Q(fechainicio__lte=fechaactual) & Q(fechafin__gte=fechaactual) & Q(numerosemana=semanaactividad)), # noqa
                fechainicio=fechainicio, fechafin=fechafin)
            detalleplanificacion.save()
        transaction.savepoint_commit(_transaccion)
        datosplanificacion['result'] = "OK"
        datosplanificacion['message'] = "¡Registro de actividad \
                            guardado correctamente!"
        messages.add_message(request, messages.SUCCESS, datosplanificacion['message'])
        # Responder solicitud pedida por AJAX
        return HttpResponse(
            json.dumps(datosplanificacion), content_type="application/json")
    except Exception as error:
        print("Error al guardar-->transaccion: " + str(error))
        print(type(error))    # la instancia de excepción
        print(error.args)     # argumentos guardados en .args
        print(error) 
        transaction.savepoint_rollback(_transaccion)
        datosplanificacion['message'] = "¡Ha ocurrido un error al tratar de ingresar los datosplanificacion de la persona!"
        datosplanificacion['error'] = "Transacción: " + str(error)
        return HttpResponse(
            json.dumps(datosplanificacion), content_type="application/json")

JAVASCRIPT - JQUERY

$("#my_form").submit(function(event){
    event.preventDefault(); //prevent default action 
    var post_url = $(this).attr("action"); //get form action url
    var request_method = $(this).attr("method"); //get form GET/POST method
    //var form_data = new FormData(this); //Encode form elements for submission
    
    let semana = document.getElementById('semana').innerHTML;
    var datos = {
        'planificacion': [],
        'semana':semana
    };

    $("#mainTable tbody tr").each(function (index) {
        var actividad, cobertura, responsable, requerido, fechainicio, fechafin;
        $(this).children("td").each(function (index2) { // Recorre cada fila y a su vez cada columna
            // Obtiene el indice de la columna en la que esta para archivar el valor en una variable
            switch (index2) {
                case 0:
                    actividad = $(this).text();
                    break;
                case 1:
                    cobertura = $(this).text();
                    break;
                case 2:
                    responsable = $(this).text();
                    break;
                case 3:
                    requerido = $(this).text();
                    break;
                case 4:
                    $(this).find("input").each(function () {
                        fechainicio = this.value
                    });
                    break;
                case 5:
                    $(this).find("input").each(function () {
                        fechafin = this.value
                    });
                    break;
            }
            //$(this).css("background-color", "#ECF8E0");
        })
        //console.log(actividad + ' - ' + cobertura + ' - ' + responsable + ' - ' + requerido + ' - ' + fechainicio + ' - ' + fechafin);
        // Añade cada uno de los datos obtenidos de la tabla dentro del arreglo de datos creando un JSON
        datos.planificacion.push({
            'actividad': actividad,
            'cobertura': cobertura,
            'responsable': responsable,
            'requerido': requerido,
            'fechainicio': fechainicio,
            'fechafin': fechafin
        });
    })
    console.log(datos)
    

    $.ajax({
        type: request_method,
        url: post_url,
        data: {'datosplaning':JSON.stringify(datos), csrfmiddlewaretoken: '{{ csrf_token }}'},
        success: function (data) {
            if (data['result'] == "OK") {
                console.log('Proceso completado')
                swal("Planificación Creada Correctamente!", "Da Clic en el boton para finalizar!", "success");
                //swal("Planificación Creada Correctamente!", "Da Clic en el boton para finalizar!", "success");
                //TablaJson(data) // Se ejecutará en el caso de que el proceso sea completado
            } else {
                console.log("¡ Error en la transacción ")
                swal ( "Oops" ,  "A ocurrido un error en el proceso!: \n Descripción: "+ data['error'] ,  "error" )
            }
    }
    }).done(function(response){ //
        $("#server-results").html(response);
    });
});

HTML
<form action="/actividad/planificacion/guardarplanificacion/" method="post" id="my_form">
  <div class="table-responsive" style="min-height: .01%; overflow-x: auto;">
    <table id="mainTable" class="table table-bordered table-striped table-hover js-basic-example dataTable">
      <thead>
        <tr>
          <th style="width: 30%">ACTIVIDAD</th>
          <th>COBERTURA</th>
          <th>RESPONSABLE</th>
          <th>REQUERIDO </th>
          <th>FECHA INICIO </th>
          <th>FECHA FIN </th>
        </tr>
      </thead>
      <tfoot>
        <tr>
          <th>ACTIVIDAD</th>
          <th>COBERTURA</th>
          <th>RESPONSABLE</th>
          <th>REQUERIDO </th>
          <th>FECHA </th>
          <th>FECHA </th>

        </tr>
      </tfoot>
      <tbody>
      </tbody>
    </table>
  </div>

  <hr />
  <div class="row clearfix">
    <div class="col-md-6">
      <button id="guardar_boton" class="btn btn-primary waves-effect" type="submit" ">GUARDAR</button>
                        </div>

                        </div>
                </form>

1 respuesta 1

2

Saludos es porque no estas enviado el ajax con el token respectivo podrias hacer algo así:

    /**
     * Permite obtener el token de django
     * 
     */
    function getCookie(name) {

      var cookieValue = null;
      if (document.cookie && document.cookie != '') {
          var cookies = document.cookie.split(';');
          for (var i = 0; i < cookies.length; i++) {
              var cookie = jQuery.trim(cookies[i]);
              if (cookie.substring(0, name.length + 1) == (name + '=')) {
              cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                  break;
              }
          }
      }
      //RETORNANDO EL TOKEN
      return cookieValue;

    }//end function getCookie

/*EJEMPLO AJAX HACIA DJANGO*/
        //token
        var csrftoken = getCookie('csrftoken');
        $.ajax({
            type: "POST",
            url: "mi_url",
            data:{
                csrfmiddlewaretoken : csrftoken, 
                parametro1:valor1,
            },
            dataType: "json",
            success: function(data) {
             console.log(data);
            },
            error: function( jqXHR, textStatus, errorThrown ) {

                if (jqXHR.status === 0) {

                    alert('Error al intentar Conectarse: Verifique su conexion a Internet.');

                } else if (jqXHR.status == 404) {

                    alert('La Pagina solicitada no fue encontrada [404]');

                } else if (jqXHR.status == 500) {

                    alert('Erro Interno [500]');

                } else if (textStatus === 'parsererror') {

                    alert('Error en el retorno de Datos. [parseJson]');

                } else if (textStatus === 'timeout') {

                    alert('Tiempo de Espera agotado');

                } else if (textStatus === 'abort') {
                    alert('Solicitud Abortada. [Ajax Request]');

                } else {
                    alert('Error desconocido: ' + jqXHR.responseText);

                }//end if 

            }//end error
        }); 

Si te fijas tengo una funcion que se encarga de obtener el token y luego se la envio x ajax para mayor referencia te facilito el link: Ajax Django

Espero te sirva suerte..!!

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.