Render a JSON in a bootstrap table Django REST framework

3

I have a model that I have called Empleado which has a foreign key to a model Direccion to keep a record of the employee's addresses.

Serializer:

from rest_framework import serializers
from models import Empleado, Direccion


class DireccionSerializer(serializers.ModelSerializer):

    class Meta:
        model = Direccion
        fields = ('id', 'pais', 'estado', 'municipio', 'ciudad', 'calle', 'colonia', 'numero_interior',
              'numero_exterior', 'codigo_postal', 'datos_adicionales')


class EmpleadoSerializer(serializers.ModelSerializer):

    direccion = DireccionSerializer()

    class Meta:
        model = Empleado
        fields = ('id', 'nombre', 'apellido_paterno', 'apellido_materno', 'fecha_nacimiento', 'rfc', 'curp',
              'direccion')

For now I am showing the records of Empleado in a table with the following cycle:

{% for empleado in object_list %}
<tr>
     <td> {{ empleado.id }}</td>
     <td> {{ empleado.nombre }} </td>
     <td> {{ empleado.apellido_paterno }} </td>
     <td> {{ empleado.apellido_materno }} </td>
     <td> {{ empleado.fecha_nacimiento|date:"Y-m-d" }} </td>
     <td> {{ empleado.curp }} </td>
     <td> {{ empleado.rfc }} </td>

     <td>
     {{ empleado.direccion.get_full_information|truncatechars:30 }}
     </td>

 </tr>

{% endfor %}

I built the following view:

class EmpleadosListApi(ListAPIView):
    serializer_class = EmpleadoSerializer

    def get_queryset(self):
        return Empleado.objects.filter(activo=1).order_by('id')

And I want to render the JSON in the table instead of using the Django tags. I tried to do it with an example I found on the Internet using the attribute data-field of Bootstrap but I did not do what I need and I have not found out how to do it. It's the first time I work with APIS, I'm quite new.

    
asked by Angie Alejo 03.02.2016 в 19:20
source

2 answers

3

Bootstrap itself does not accept those properties, but you can use the bootstrap tables library , it's Say, you need to add the references to your CSS and JS, in addition to invoking it as you need

For example from a json direct (from the official documentation ) where data-field is the name of the element in json.

It is important to note that it is generated with the following code:

$(function () {
    $('#table').bootstrapTable({
       data: data
    });
});

Where (with Jquery) the page is loaded, the HTML element of the table is selected using the id and the json that is in the variable data is applied with the method bootstrapTable

In your case you would have to apply it when you get the information of your json (I assume that in the success of your ajax) and do not forget to convert it to a javascript object since you will probably get it as text

    
answered by 03.02.2016 / 19:58
source
0

Thanks, I did it by calling the JSON items and injecting the attributes to the <td> tags, I hope somebody serves them.

<script>
$(document).on('ready',function(){
    $.ajax({url: "{% url 'empleados:empleados_list_api' %}",
        data:{lista: 'empleados'},
        dataType:"json",
        type:"GET"
    }).done(function(data){

        $.each(data, function(index, item){

            var direccion = '';
            var fdireccion = '';
            if (item.direccion.calle.length != 0)direccion += item.direccion.calle;
            if (item.direccion.numero_interior.length != 0)direccion += ' No. Int. ' + item.direccion.numero_interior;
            if (item.direccion.numero_interior.length != 0 && item.direccion.numero_exterior.length != 0)direccion += ' ,';
            if (item.direccion.numero_exterior.length != 0)direccion += ' No. Ext. ' + item.direccion.numero_exterior;
            if (item.direccion.colonia.length != 0)direccion += ', Colonia ' + item.direccion.colonia;
            if (item.direccion.codigo_postal.length != 0)direccion += ', C.P. ' + item.direccion.codigo_postal;
            if (item.direccion.ciudad.length != 0)direccion += ', ' + item.direccion.ciudad;
            if (item.direccion.municipio.length != 0)direccion += ', ' + item.direccion.municipio;
            if (item.direccion.estado.length != 0)direccion += ', ' + item.direccion.estado;
            if (item.direccion.pais.length != 0)direccion += ', ' + item.direccion.pais;
            if (direccion.length>30)fdireccion = $.trim(direccion).substring(0, 30).split(" ").slice(0, -1).join(" ") + "...";
            else fdireccion=direccion;
            var $tr = $('<tr>').append(
                    $('<td>').text(item.id),
                    $('<td>').text(item.nombre),
                    $('<td>').attr({'class':'hidden-xs','style':'width: 15%;'}).text(item.apellido_paterno),
                    $('<td>').attr({'class':'hidden-xs','style':'width: 15%;'}).text(item.apellido_materno),
                    $('<td>').attr({'class':'hidden-xs','style':'width: 15%;'}).text(item.fecha_nacimiento),
                    $('<td>').attr({'class':'hidden-xs','style':'width: 15%;'}).text(item.curp),
                    $('<td>').attr({'class':'hidden-xs','style':'width: 15%;'}).text(item.rfc),
                    $('<td>').attr({'class':'hidden-xs','style':'width: 15%;','data-toggle':'tooltip','title':''+direccion}).text(fdireccion),
                    $('<td>').attr('class','text-center').append(
                            $('<div>').attr('class','btn-group').append(
                                $('<a>').attr(
                                        {   'class':'btn btn-xs btn-default',
                                            'type':'button',
                                            'data-toggle':'tooltip',
                                            'title':'Editar Empleado'
                                        }
                                ).append(
                                        $('<i>').attr('class','fa fa-pencil')).data('id',item.id).click(function(){
                                    var id = $(this).data('id');
                                    window.location = 'edit/'+item.id;
                                }),
                                $('<a>').attr(
                                        {   'class':'btn btn-xs btn-default',
                                            'type':'button',
                                            'data-toggle':'tooltip',
                                            'title':'Eliminar Empleado'
                                        }
                                ).append(
                                        $('<i>').attr('class','fa fa-times')).data('id',item.id).click(function(){
                                    var id = $(this).data('id');
                                    window.location = 'delete/'+item.id;
                                })
                            ))
            ).appendTo('#tabla_lista_empleados');
        });
    });
});
</script>
    
answered by 03.02.2016 в 23:08