1
I am performing the passage of lines that will compose a table in the Datatables pattern through Django.
If I do the DOM insertion, I can handle it by calling the Datatables function via JS.
The problem is that I will need to update this table, so I decided to pass the rows in JSON format as I can make an AJAX request to my backend, take the new JSON and update the table.
In my views.py I am returning a JSON in the POST request:
from django.views.generic.list import ListView
from django.http import JsonResponse
from django.shortcuts import render
from django.utils import timezone
from .models import Convenio
class ListaConveniosView(ListView):
model = Convenio
template_name = '_convenio01.html'
# def get_context_data(self, **kwargs):
# print(self)
# context = super().get_context_data(**kwargs)
# context['now'] = timezone.now()
# return context
def get(self, request, *args, **kwargs):
print("O GET:")
if request.is_ajax():
return JsonResponse({'method': 'get'}, status=200)
else:
return render(request, self.template_name)
def post(self, request, *args, **kwargs):
print("O POST")
card_text = request.POST.get('uma_chave')
print(card_text)
return JsonResponse(
{
"data":
[
{
"codigo": "1",
"titulo": "Tiger",
"faturavel": "0"
},
{
"codigo": "21",
"titulo": "HHH",
"faturavel": "1"
}
]
},
status=200)
To play I also left a text file data.json with the data:
{
"data":
[
{
"codigo": "1",
"titulo": "Unimed",
"faturavel": "0"
},
{
"codigo": "2",
"titulo": "Outro",
"faturavel": "1"
}
]
}
My front is receiving a Javascript with two functions. The first sends to the datatables the path of the data.json file, which takes the feeds the table.
function dataVai(passou=0, listaJson) {
console.log('Passou = ' + passou)
console.log('listaJson = ' + listaJson)
var convenio_root = $("#link-assets")[0].href
var link_static = $("#link-static")[0].href
console.log(convenio_root)
if(passou===0){
listaJson = link_static + 'rotinas/convenios/data.json'
}
console.log('ListaFull: ' +listaJson)
// Coloca uma caixa de busca em cada coluna
$('#convenioLista tfoot th').each( function () {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
} );
// DataTable
var table = $('#convenioLista').DataTable({
"language": {
"url": "//cdn.datatables.net/plug-ins/1.10.22/i18n/Portuguese-Brasil.json"
},
'ajax': listaJson,
"columns": [
{ "data": "codigo" },
{ "data": "titulo" },
{ "data": "faturavel" }
],
// dom: 'Bfrtip',
buttons: [
'copy', 'excel', 'pdf'
],
initComplete: function () {
// Executa a busca
this.api().columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change clear', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
} );
} );
}
});
}
The second function makes a post that is received by my view up there and will have the JSON that was returned by it in the response variable.
function serverSide() {
$('#convenioLista').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "",
"type": "POST",
data: {
uma_chave: 'um texto enviado por ajax',
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success: function(response){
resposta = response
console.log('Deu certo meu amigo, a resposta voltou!')
console.log(response)
//Aqui eu tenho resposta, como o meu json. Só preciso chamar o DataTables e repassar essa variável/JSON
}
},
"columns": [
{ "data": "codigo" },
{ "data": "titulo" },
{ "data": "faturavel" }
]
} )
}
When I open the Chrome console, if I call the dataVai() function, my table is filled.
However if I call the serverside() function it is processing infinitely and does not fill the table.
I have the impression that the problem is with the data format that Django returns. I believe it is not in the pattern expected by Datatables.
I made a console.log playing in the response variable:
I am very grateful if someone can point me a way, I am very doubtful and researching for two days now.