When passing JSON object received from DJANGO to Datatables with Javascript the table is not populated generating infinite processing

Asked

Viewed 66 times

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.

DataTables - dataVai()

However if I call the serverside() function it is processing infinitely and does not fill the table.

DataTables - serverSide()

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: Variável Resposta

I am very grateful if someone can point me a way, I am very doubtful and researching for two days now.

1 answer

0


I managed to solve the problem.

I had to change the format of the return data in my view:

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)

        lista = [[ "99", "SUS", "1"],
                [ "88", "Unimed", "0"]]

        return JsonResponse(            
            {
                "data": lista
            },
            status=200, safe=False)

After making a POST request, I receive the data in a dataset variable and pass to the function, example:

var dataSet = [
    [ "55", "Architect", "1"],
    [ "77", "Accountant", "0"]
];

function dt() {
    $('#convenioLista').DataTable( {
        data: dataSet,
        columns: [
            { title: "Código" },
            { title: "Título" },
            { title: "Faturável" }
        ]
    } );
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.