I tried to make a listing with ajax and data-table

I tried to make a listing with ajax and data-table

gadea2021gadea2021 Posts: 1Questions: 1Answers: 0
edited July 2020 in Free community support

Good afternoon, I tried to make a listing with ajax and data-table, but I cannot get that when editing or deleting a record, the id of my model is not recognized.

models

class Client(models.Model):

    id = models.AutoField(primary_key=True, editable=False, unique=True)
    type_identification = models.CharField(verbose_name='Tipo de identificación', max_length=210, choices=type_identification, default='', blank=False, null=False)
    identification = models.CharField(max_length=10, unique=True, verbose_name='Identificación', blank=False, null=False)
    dv = models.CharField(verbose_name='Dv', max_length=2, blank=False, null=False, )
    name_client_1 = models.CharField(verbose_name='Nombre', max_length=150,  blank=False, null=False)
    name_client_2 = models.CharField(verbose_name='Segundo nombre', max_length=150, blank=True, null=True)
    last_names_cliente = models.CharField(verbose_name='Apellidos', max_length=150, blank=False, null=False)
    type_person = models.CharField(verbose_name='Tipo de persona', max_length=210, choices=type_person, default='', blank=False, null=False)
    type_responsibility = models.CharField(verbose_name='Tipo de responbilidad', max_length=210, choices=responsibility, default='', blank=False, null=False)
    address = models.CharField(verbose_name='Dirección', max_length=150, null=True, blank=True)
    country = models.ForeignKey(Country, on_delete=models.CASCADE)
    departament = models.ForeignKey(Dptos, on_delete=models.CASCADE)
    city = models.ForeignKey(City, on_delete=models.CASCADE)
    email = models.EmailField(verbose_name='Correo', max_length=210, blank=False, null=False)
    tel_1 = models.CharField(verbose_name='Teléfono 1', max_length=10, null=True, blank=True)
    tel_2 = models.CharField(verbose_name='Teléfono 2', max_length=10, null=True, blank=True)
    mobile = models.CharField(verbose_name='Celular', max_length=10, blank=False, null=False)
    client = models.BooleanField(verbose_name='Cliente')
    provider = models.BooleanField(verbose_name='Proveedor')

    def __str__(self):
        return self.name_client_1

    def toJSON(self):
        item = model_to_dict(self)
        return item

    class Meta:
        verbose_name = 'Cliente'
        verbose_name_plural = 'Clientes'

views

class ClientListView(ListView):
    model = Client
    template_name = 'client/list_client.html'
    context_object_name = 'clients'

    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        data = {}
        try:
            action = request.POST['action']
            if action == 'searchdata':
                data = []
                for i in Client.objects.all():
                    data.append(i.toJSON())
            else:
                data['error'] = 'Ha ocurrido un error'
        except Exception as e:
            data['error'] = str(e)
        return JsonResponse(data, safe=False)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = 'Listado de clientes'
        context['list_url'] = reverse_lazy('client_create')
        return context

urls

urlpatterns = [

path('client/edit/<int:pk>/', ClientUpadateView.as_view(), name='client_update'),
path('client/delete/<int:pk>/', ClientDeleteView.as_view(), name='client_delete'),

]

script

<script>
$(function () {
    $('#html5-extension').DataTable({
        responsive: true,
        autoWidth: false,
        dom: '<"row"<"col-md-12"<"row"<"col-md-6"B><"col-md-6"f> > ><"col-md-12"rt> <"col-md-12"<"row"<"col-md-5"i><"col-md-7"p>>> >',
            buttons: {
                buttons: [
                    { extend: 'copy', className: 'btn' },
                    { extend: 'csv', className: 'btn' },
                    { extend: 'excel', className: 'btn' },
                    { extend: 'print', className: 'btn' }
                ]
            },
        destroy: true,
        deferRender: true,
        ajax: {
            url: window.location.pathname,
            type: 'POST',
            data: {
                'action': 'searchdata'
            },
            dataSrc: ""
        },
        columns: [
            { "data": "id"},
            { "data": "name_client_1"},
            { "data": "last_names_cliente"},
            { "data": "identification"},
            { "data": "mobile"},
            { "data": "email"},
            { "data": "city"},
        ],
         "oLanguage": {
                "oPaginate": { "sPrevious": '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-left"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>', "sNext": '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-right"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>' },
                "sInfo": "Mostrando pag. _PAGE_ de _PAGES_",
                "sSearch": '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-search"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>',
                "sSearchPlaceholder": "Buscar...",
                "sLengthMenu": "Results :  _MENU_",
            },
        columnDefs: [
            {
                targets: [6],
                class: 'text-center',
                orderable: false,
                render: function (data, type, row) {
                    var buttonss = '<a href="/erp/client/edit/' + row.id + '/" class="dropdown-item" >Editar</a>';
                    return buttonss;
                }
            },
        ],
        initComplete: function(settings, json) {

        }
    });
});
</script>

html

<table id="html5-extension" class="table table-hover non-hover" style="width:100%">

    <thead>
    <tr>
    <th>Id</th>
    <th>Nombre</th>
    <th>Apellidos</th>
    <th>Identificación</th>
    <th>Celular</th>
    <th>Correo</th>
    <th>Opciones</th>
</tr>
    </thead>

    <tbody>
    </tbody>

</table>

    ![](https://datatables.net/forums/uploads/editor/t4/nn6rbozpjjzq.png "")


Edited by Colin - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Is this using Editor? I can't see any reference to it.

    Also, have you followed the diagnostic instructions that are in the URL in the error. That's the best place to start.

    Colin

This discussion has been closed.