lundi 17 juin 2019

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

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-' type="checkbox" value="" 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




Aucun commentaire:

Enregistrer un commentaire