Daniel Vieira
Daniel Vieira

Reputation: 471

Submitting variable checkbox form selection in django when choice options are not hardcoded

I am hoping someone can help on this. I am trying to POST submit a checkbox selection in a django template, the only difference that the number of checkbox options is variable, i.e not predefined in the django form. Could you please help me how to do this? thanks so much:

views.py:

if request.method == 'POST':
    list_of_files=request.POST.getlist('filetouse')
    print(list_of_files)
else:

template:

<td>
    <form action="" method="post">
        <div class="form-check">
            <input type="checkbox" name="filetouse" class="form-check-input" id="file-{{ key }}">
            <label class="form-check-label" for="FileSelect1">Select</label>
        </div>
    </form>
</td>

so I have a variable ID for each checkbox (from the key object attribute that I handed over to the template, my plan being to then do something such as:

if request.method == 'POST':
    #gives list of id of inputs 
    list_of_input_ids=request.POST.getlist('filetouse')

but I cannot figure out how to do this POST submission, thanks so much for your help !

Upvotes: 0

Views: 563

Answers (1)

MD. Khairul Basar
MD. Khairul Basar

Reputation: 5110

In your template name all the checkboxes filetouse and make sure every checkbox has a different value, so that you can identify the objects with that value preferably the id of the object.

<td>
    <form action="" method="post">
        <div class="form-check">
            <input type="checkbox" name="filetouse" value="{{ some_id }}" class="form-check-input" id="file-{{ key }}">
            <label class="form-check-label" for="FileSelect1">Select</label>
        </div>
    </form>
</td>

When you get the values using .getlist() you will get a list which contains the values of the selected checkboxes. Now, you can get the objects from those ids and do whatever you want.

Upvotes: 1

Related Questions