Search code examples
djangodjango-datatable

Add row Id in Django data table


I am using django datatable the data that come from server has the following format:

[ ['id_value','data col1','data col2',...]
   .
   .
   .]

I am try to make id to every row as follow:

'rowId': 1,

but it doesn't work

my html code:

<table id="mainDataTable" class="table table-responsive-md table-{{ documentvals.table_type }}">
                        <thead>
                        <tr>
                            {% for field in list_fields %}
                                <th> {{ field }}</th>
                            {% endfor %}
                        </tr>
                        </thead>
                        <tbody>

                        </tbody>
                        <tfoot>
                        <tr>
                            {% for field in list_fields %}
                                <th> {{ field }}</th>
                            {% endfor %}
                        </tr>
                        </tfoot>
                    </table>
            

Also, my js code is:

let _columns= [
    {% for field in list_fields %}
        { "data": '{{ field }}' },
        {% endfor %}
]

$('#mainDataTable').DataTable({
        "paging": true,
        "lengthChange": true,
        "searching": true,
        "ordering": true,
        "info": true,
        "columns": _columns,
        "autoWidth": false,
        "responsive": true,
        "aaSorting": [],
        "pageLength": pag,
        "bProcessing": true,
        "bServerSide": true,
        "ajax": {
            "url": mainUrl,
        },
        'rowId': 1,
        "pagingType": "full_numbers",
        destroy: true,
    });

I did not want to edit Django datatable library.


Solution

  • Based on my understanding, I think you are trying to give something like a S.No. to your table in the form of rowId for whatever purpose.

    Something like enumerate in python might be needed to achieve this, In this case you can use forloop counters in django templating, available in multiple variants as follows enter image description here

    Just for reference, Here is how you can use this in your _columns variables for loop of js file

    let _columns= [
        {% for field in list_fields %}
            { "data": '{{ field }}', "rowId": '{{forloop.counter}}' },
        {% endfor %}
    ]
    

    Similarly, it can be used in your table as well.

    I highly suggest you to have a look a official django templating forloop documentation.