Как выбрать / отменить выбор / удалить несколько элементов Django в таблице с тем же флажком? - PullRequest
1 голос
/ 17 июня 2019

У меня есть эта таблица элементов с их деталями, и я реализовал метод «выбора» нескольких элементов с помощью кнопки отправки, который передает все отмеченные флажки для каждого элемента.

Это код для флажка:

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

Как видите, я передал quiz.id в значение флажка. Это моя кнопка отправки, которую я использую:

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

Здесь я не упомянул, что будет делать эта кнопка, кроме как отправить. Эта функция обрабатывает ввод данных с помощью кнопки отправки.

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')

Как видите, моя функция 'post' принимает только викторины из-за этой строки request.POST.getlist('quiz-pids'). Теперь мой вопрос, я также хочу удалить и отменить выбор моих товаров. Но, поскольку моя функция может принимать только викторины, я не могу просто создать еще одну кнопку для этого.


Что я пробовал

Я пытался добавить больше функций:

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()

Но, поскольку каждый флажок, который я имею перед моими элементами, имеет имя name='quiz-pids', я не могу создать список удаленных_элементов или список unselect_items. Я не могу дать три разных флажка для каждого элемента. Что мне делать?

Вот моя полная функция html и views:

@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-шаблон:

{% 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 %}

У кого-нибудь есть сомнения? или нужна дополнительная информация?

...