0

I have a table with checkboxes and I would like to be able to delete or edit a specific field value for all the selected rows in the table.

Here's an example table that would be awesome to recreate but I have not found examples anywhere how this may work in the view and template. https://examples.bootstrap-table.com/#

My current view, which is working with a table. Where can I start to make the leap from a basic table to an interactive one like in the example above?

Views.py

class EntryList(LoginRequiredMixin, ListView):
    context_object_name = 'entry_list'
    paginate_by =  100
    # paginate_by =  5
    #ordering = ['-pk']
    model = Entry
    template_name = "portfolios/entry_list.html"

    def get_queryset(self):
        return Entry.objects.filter(created_by=self.request.user).order_by('-pk')

    def post(self, request, *args, **kwargs):
        ids = self.request.POST.get('ids', "")
        # ids if string like "1,2,3,4"
        ids = ids.split(",")
        try:
            # Check ids are valid numbers
            ids = map(int, ids)
        except ValueError as e:
            return JsonResponse(status=400)
        # delete items
        self.model.objects.filter(id__in=ids).delete()
        return JsonResponse({"status": "ok"}, status=204)

entry_list.html

{% extends "dashboard/base.html" %}
{% load i18n %}
{% block content %}

<!-- Page Heading -->
<div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h2 class="text-gray-800">{% block title %}{% trans "Imported Entries" %}{% endblock %}</h2>
    <a role="button" class="btn btn-success" href="{% url 'import' %}"><i
            class="fas fa-plus-circle"></i> Import New Entires</a>
</div>

<!-- Content Row -->
<div class="row">

    <div class="col-md-12">
        <div class="card shadow mb-4">
            <div class="card-body">
                <div id="dataTable_wrapper" class="dataTables_wrapper dt-bootstrap4">
                    <div class="row">
                    </div>
                    <div class="row">
                        <div class="col-sm-12">
                            <table class="table-responsive-xl table table-hover table-striped table-bordered dataTable" id="dataTable" width="100%"
                                   cellspacing="0" role="grid" aria-describedby="dataTable_info">
                                <thead>
                                <tr role="row">
                                    <th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
                                        colspan="1" aria-label="" style="">
                                    </th>
                                    <th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
                                        colspan="1" aria-label="" style="">ID
                                    </th>
                                    <th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
                                        colspan="1" aria-label="" style="">Date
                                    </th>
                                    <th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
                                        colspan="1" aria-label="" style="">Trade
                                    </th>
                                    <th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
                                        colspan="1" aria-label="" style="">Type
                                    </th>
                                    <th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
                                        colspan="1" aria-label="" style="">Symbol
                                    </th>
                                    <th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
                                        colspan="1" aria-label="" style="">Amount
                                    </th>
                                    <th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
                                        colspan="1" aria-label="" style="">Price
                                    </th>
                                    <th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
                                        colspan="1" aria-label="" style="">Fee
                                    </th>
                                    <th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
                                        colspan="1" aria-label="" style="">Reg Fee
                                    </th>
                                    <th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1"
                                        colspan="1" aria-label="" style="">Ref
                                    </th>
                                </tr>
                                </thead>
                                <tbody>
                                {% for entry in object_list %}
                                <tr role="row">
                                    <td class="text-center">
                                        <div class="custom-control-lg custom-control custom-checkbox">
                                            <input type="checkbox" class="custom-control-input form-control-lg" data-id="{{ entry.pk}}" id="check{{ entry.pk }}">
                                            <label class="custom-control-label" for="check{{ entry.pk }}"></label>
                                        </div>
                                    </td>
                                    <td><a href="{% url 'entry-update' entry.pk %}">{{ entry.pk }}</a></td>
                                    <td>{{ entry.date | date:"M d, Y h:i:s A"}}</td>
                                    <td><a href="/trade/{{ entry.trade.id }}">{{ entry.trade.id }}</a></td>
                                    <td>{{ entry.entry_type }}</td>
                                    <td>{{ entry.symbol }}</td>
                                    <td>{{ entry.amount }}</td>
                                    <td>{{ entry.price }}</td>
                                    <td>{{ entry.fee }}</td>
                                    <td>{{ entry.reg_fee }}</td>
                                    <td>{{ entry.transaction_id }}</td>
                                </tr>
                                {% endfor %}

                                </tbody>
                            </table>
                        </div>
                    </div>
                    <!--Pagination-->
                    <div class="row">
                        <div class="col-12 ">


                            <div class="pagination">
                                <span class="step-links">
                                    {% if page_obj.has_previous %}
                                        <a href="?page=1">&laquo; first</a>
                                        <a href="?page={{ page_obj.previous_page_number }}">previous</a>
                                    {% endif %}

                                    <span class="current">
                                        Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
                                    </span>

                                    {% if page_obj.has_next %}
                                        <a href="?page={{ page_obj.next_page_number }}">next</a>
                                        <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a>
                                    {% endif %}
                                </span>
                            </div>


                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>

</div>
{% endblock content %}
Alex Winkler
  • 469
  • 4
  • 25

1 Answers1

1

It depends on how you've implemented your frontend, but assuming you have standard django templates, then I would suggest taking a look at datatables. There's quite a lot to it, but it is very stable and has a decent feature set, and the documentation is good. You can style it how you want using bootstrap.

Also, you link to Bootstrap Table - that should be the same principle. Read through the docs to understand how it works, and you will have to use Django template tags to render the data in the table.

Note that the table is implemented using HTML / Jquery, so it is not directly related to Django. All you need to do is to iterate over the django objects in your template (example)

EDIT

How to delete a selected row?

Suppose you could select N rows, and then click a button to delete all of these rows.

This could work as follows:

  • Add a handler to the delete button:
  • identify the selected rows
  • send an Ajax request to delete the rows
  • handle the success response to remove the deleted rows from the table
// SIMPLIFIED CODE SAMPLE

$("#delete-btn").click(function () {
  var selectedRows = table.rows({"selected": true});

  var dataObj = {
    // parse selectedRows to get object ids
  }
  
  $.ajax({
      url: '/api/delete-rows/',
      type: 'post',
      data: dataObj,
      success: function (data, status, xhr) {
        // remove the selected rows from the view
        table.rows({"selected": true}).deselect().remove().draw();
      }
    })
}

How to select rows and quickly change a field for all of the selected rows?

The same principle here. Once rows are selected, have a handler which identifies the selected rows, then you can use the datatables api to update given fields (docs).

Matthew Hegarty
  • 3,791
  • 2
  • 27
  • 42
  • My table is working fine, it's in bootstrap and there's a checkbox col already. My problem is making the table have actions. How to delete a selected row? How to select rows and quickly change a field for all of the selected rows? – Alex Winkler Oct 31 '20 at 16:51
  • Thanks for the updated answer still working through it! I'll update here if I have any questions but for now, this looks to be 100% the right direction. I'll have to consider which direction is best for my case the datatables or the template tags approach. If you have any feedback as to which is ideal I'm always open to feedback. – Alex Winkler Nov 02 '20 at 06:04
  • note that you can use template tags and datatables together - datatables is just a library to help with most aspects of rendering tables. It can be tricky to get datatables working, but there is decent documentation and a dedicated forum, so worth the time investment IMO – Matthew Hegarty Nov 02 '20 at 11:46
  • I can't seem to get datatables to properly work.. I'm not sure where the issues are integrating it here's where I'm currently stuck at https://stackoverflow.com/questions/64692777/datatables-pagination-does-not-show – Alex Winkler Nov 06 '20 at 09:38
  • using the bootstrap theme I changed out "selected" to "active" but still not highlighting the right rows. Any idea? https://datatables.net/forums/discussion/65425/bootstrap-table-select-row-active-class/p1?new=1 – Alex Winkler Nov 11 '20 at 06:32
  • I suggest create a new specific SO post for this issue - I'm in the [chat](https://chat.stackoverflow.com/rooms/224399/datatables) today - will help if I can – Matthew Hegarty Nov 11 '20 at 07:51
  • Hey Matthew, I'm stuck yet again ha.. https://stackoverflow.com/q/64870736/8315752 Maybe you know where I need to improve the code you started from above? – Alex Winkler Nov 17 '20 at 09:40