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>