How to select/unselect/delete multiple django items in a table with the same checkbox?

我的未来我决定 提交于 2019-12-24 12:44:01

问题


I have this table of items with their details, and I have implemented a method to 'select' a few items using a submit button, which submits all checked checkboxes on each item.

This is the code for the checkbox:

<input name='quiz-pids' id='checkbox-{{ quiz.id }}' type="checkbox" value="{{ quiz.id }}" required>

As you can see, I have passed the quiz.id in the checkbox value. This is my submit button I am using:

<input type="submit" class="btn btn-primary select-btn myitems-select-btn"
                               value='Finalize Items'
                               required>

Here, I have not mentioned what this button will do except than submit. This is the function which processes the data input by submit button.

class UploadedItems(ListView):
    model = ItemBatch
    ordering = ('uploaded',)
    context_object_name = 'plan'
    template_name = 'classroom/teachers/item_list.html'

    def post (self, request, *args, **kwargs):
        # get the selected quizs
        quizs = request.POST.getlist('quiz-pids')

        # retrieves thoses quizes from the database:
        print("pids returned are ", quizs)
        # items = ItemBatch.objects.filter(pid__in=quizs)

        for i in quizs:
            print("before", i)
            i = get_object_or_404(ItemBatch, id=i)
            i.rtd = 'True'
            i.save()
            print("after", i.truck_type)  # print("items are",items)

        return redirect('teachers:upload_batch')

As you can see, my function 'post' accepts only quiz-pids because of this line request.POST.getlist('quiz-pids'). Now my question is, I also want to delete and unselect my items. But, because my function can only accept quiz-pids, I cannot just create another button for that.


What I tried

I tried adding more functions:

def post (self, request, *args, **kwargs):
    # get the selected quizs
    quizs = request.POST.getlist('quiz-pids')
    deleted_items = request.POST.getlist('delete-pids')
    unselect_items = request.POST.getlist('unselect-pids')
    # retrieves thoses quizes from the database:
    print("pids returned are ", quizs)
    # items = ItemBatch.objects.filter(pid__in=quizs)

    for i in quizs:
        print("before", i)
        i = get_object_or_404(ItemBatch, id=i)
        i.rtd = 'True'
        i.save()
        print("after", i.truck_type)  # print("items are",items)

    for j in unselect_items:
        j = get_object_or_404(ItemBatch, id=i)
        j.rtd = 'False'
        j.save()

    for k in deleted_items:
        k = get_object_or_404(ItemBatch, id=i)
        k.delete()
        k.save()

But, because every checkbox I have in front of my items, has the name name='quiz-pids', I am not able to generate a deleted_items list or unselect_items list. I cannot possibly give three different checkboxes to every item. What should I do?

Here is my complete html and views function:

@method_decorator([login_required, teacher_required], name='dispatch')
class UploadedItems(ListView):
    model = ItemBatch
    ordering = ('uploaded',)
    context_object_name = 'plan'
    template_name = 'classroom/teachers/item_list.html'

    def get_queryset (self):
        return ItemBatch.objects.filter(uploaded_by=self.request.user)

    def get_context_data (self, **kwargs):
        context = super().get_context_data(**kwargs)
        latest = ItemBatch.objects.filter(uploaded_by=self.request.user).order_by('-time').annotate(
            truncated_time=Trunc('time', 'minute', output_field=DateTimeField()))

        context['last'] = ItemBatch.objects.filter(uploaded_by=self.request.user).annotate(
            truncated_time=Trunc('time', 'minute', output_field=DateTimeField())).filter(
            truncated_time=Subquery(latest.values('truncated_time')[:1])).order_by('-rtd')
        return context

    def post (self, request, *args, **kwargs):
        # get the selected quizs
        quizs = request.POST.getlist('quiz-pids')
        deleted_items = request.POST.getlist('delete-pids')
        unselect_items = request.POST.getlist('unselect-pids')
        # retrieves thoses quizes from the database:
        print("pids returned are ", quizs)
        # items = ItemBatch.objects.filter(pid__in=quizs)

        for i in quizs:
            print("before", i)
            i = get_object_or_404(ItemBatch, id=i)
            i.rtd = 'True'
            i.save()
            print("after", i.truck_type)  # print("items are",items)

        for j in unselect_items:
            j = get_object_or_404(ItemBatch, id=i)
            j.rtd = 'False'
            j.save()

        for k in deleted_items:
            k = get_object_or_404(ItemBatch, id=i)
            k.delete()
            k.save()

        print("pids converted are ", quizs)

        return redirect('teachers:upload_batch')

HTML template:

{% extends 'base2.html' %}
{% load static %}
{% load tz humanize %}
{% timezone "Asia/Kolkata" %}
    {% block content %}
        <h2>Orders</h2>
        {% include 'classroom/teachers/inventory_header.html' with active='myitems' %}
        <h2 class="align-left"> Your Last Uploaded Items</h2>
        {#<a href="{% url 'teachers:quiz_add' %}" class="btn btn-primary mb-3" role="button">Post New Bid</a>#}
        <div class="card last-items">
            <form method="post" novalidate>
                {% csrf_token %}
                <table class="table table-striped mb-0" id="items">
                    <thead>
                    <tr>
                        <th>Select</th>
                        <th>Name</th>
                        <th>SKU ID</th>
                        <th>Quantity</th>
                        <th>Dimensions</th>
                        <th>Volume/Weight</th>
                        <th>Origin</th>
                        <th>Destination</th>
                        <th>Type</th>
                        <th>Uploaded</th>
                        <th>Dispatch Status</th>
                    </tr>
                    </thead>

                    <tbody>
                    <input type="checkbox" id="selectall" class="css-checkbox btn btn-primary" name="selectall"/>Select
                    All

                    {% for quiz in last %}
                        <input type="submit" class="btn btn-primary select-btn myitems-select-btn"
                               value='Finalize Items'
                               required>

                        <input type="submit" class="btn btn-primary select-btn myitems-select-btn"
                               value='Unselect Items'
                               required>

                        <input type="submit" class="btn btn-primary select-btn myitems-select-btn"
                               value='Delete Items'
                               required>

                        <a href="{% url 'teachers:pack_it' %}"
                           class="btn btn-primary mb-3 myitems-select-btn  {% if quiz.rtd == 0 %} disabled {% endif %}"
                           role="button">Plan Vehicles</a>



                        <tr class="{% if quiz.rtd == True %} active{% endif %} {% if quiz.is_dispatched == True %} dispatched{% endif %}">
                            <td class="align-middle"><input name='quiz-pids' id='checkbox-{{ quiz.id }}'
                                                            type="checkbox" value="{{ quiz.id }}" required
                                    {% if quiz.is_dispatched == 1 %} disabled{% endif %} ></td>

                            <td class="align-middle">{{ quiz.name }}</td>
                            <td class="align-middle">{{ quiz.pid }}</td>
                            <td class="align-middle">{{ quiz.quantity }}</td>
                            <td class="align-middle">{{ quiz.length }}x{{ quiz.width }}x{{ quiz.height }}</td>
                            <td class="align-middle">{{ quiz.volume|truncatechars:8 }}/{{ quiz.weight }}</td>
                            <td class="align-middle">{{ quiz.origin }}</td>
                            <td class="align-middle">{{ quiz.destination }}</td>
                            <td class="align-middle">{{ quiz.truck_type }}</td>
                            <td class="align-middle">{{ quiz.time|naturaltime }}</td>
                            <td class="align-middle">{{ quiz.is_dispatched|yesno:"Dispatched,Ready to Dispatch" }}</td>
                        </tr>


                    {% endfor %}


                    </tbody>

                </table>
            </form>
        </div>

        <br>
        <br>
        <h2 class="align-left">All your Uploaded Items</h2>
        <br>

        <div class="card">
            <table class="table table-striped mb-0" id="items">
                <thead>
                <tr>
                    <th>Select</th>
                    <th>Name</th>
                    <th>SKU ID</th>
                    <th>Quantity</th>
                    <th>Dimensions</th>
                    <th>Volume/Weight</th>
                    <th>Origin</th>
                    <th>Destination</th>
                    <th>Type</th>
                    <th>Uploaded</th>
                    <th>Dispatch Status</th>
                </tr>
                </thead>
                <tbody>
                <form method="post" novalidate>
                    {% csrf_token %}
                    {% for quiz in plan %}
                        <input type="submit" class="btn btn-primary select-btn myitems-select-btn"
                               value='Finalize Items'
                               required>

                        <a href="{% url 'teachers:pack_it' %}"
                           class="btn btn-primary mb-3 myitems-select-btn  {% if quiz.rtd == 0 %} disabled {% endif %}"
                           role="button">Plan Vehicles</a>



                        <tr class="{% if quiz.rtd == True %} active{% endif %} {% if quiz.is_dispatched == True %} dispatched{% endif %}">
                            <td class="align-middle"><input name='quiz-pids' id='checkbox-{{ quiz.id }}'
                                                            type="checkbox" value="{{ quiz.id }}" required
                                    {% if quiz.is_dispatched == 1 %} disabled{% endif %} ></td>

                            <td class="align-middle">{{ quiz.name }}</td>
                            <td class="align-middle">{{ quiz.pid }}</td>
                            <td class="align-middle">{{ quiz.quantity }}</td>
                            <td class="align-middle">{{ quiz.length }}x{{ quiz.width }}x{{ quiz.height }}</td>
                            <td class="align-middle">{{ quiz.volume }}/{{ quiz.weight }}</td>
                            <td class="align-middle">{{ quiz.origin }}</td>
                            <td class="align-middle">{{ quiz.destination }}</td>
                            <td class="align-middle">{{ quiz.truck_type }}</td>
                            <td class="align-middle">{{ quiz.time|naturaltime }}</td>
                            <td class="align-middle">{{ quiz.is_dispatched|yesno:"Dispatched,Ready to Dispatch" }}</td>
                        </tr>
                        <tr>
                            {% empty %}
                            <td class="bg-light text-center font-italic" colspan="9">You haven't uploaded any items yet.
                            </td>
                        </tr>

                    {% endfor %}


                </form>


                </tbody>
            </table>
        </div>

        <link rel="stylesheet" href="http://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">
        {#        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>#}
        <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>

        <script>
            $(document).ready(function () {
                $('#items').DataTable({
                    "pagingType": "full_numbers",
                    "bDestroy": true
                });
            });
        </script>


        <script>

            $('#selectall').click(function () {
                var checkedStatus = this.checked;
                $('input:checkbox').each(function () {
                    $(this).prop('checked', checkedStatus);
                });
            });

        </script>

    {% endblock %}
{% endtimezone %}

Anybody has any doubts? or need more information?

来源:https://stackoverflow.com/questions/56626985/how-to-select-unselect-delete-multiple-django-items-in-a-table-with-the-same-che

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!