how to get selected value from checkbox into views.py and convert into excel?

Question:

index.html

  <form method="GET">
     <div class="form-row">
        <div class="custom-control custom-checkbox mb-10 popup-sec-chk">
            <input class="custom-control-input form-control inputfld" type="checkbox" id="date_inquiry" name="excelfields[]" value="dateofInquiry">
            <label class="custom-control-label" for="date_inquiry">Date of Inquiry</label>
        </div>
            
        <div class="custom-control custom-checkbox mb-10 popup-sec-chk">
            <input class="custom-control-input inputfld" type="checkbox" id="callers_name" name="excelfields[]" value="Callers name">
            <label class="custom-control-label" for="callers_name">Caller's Info</label>
        </div>
    </div>
    
    <div class="modal-footer">
        <a type="submit" href="{% url 'excelExport' %}" class="btn btn-primary" >Select</a>
    </div>
  </form>

views.py

def excelExport(request):
    try:
        if request.method == 'GET':
            checkedField = request.GET.getlist('excelfields[]')
            print("Checked list data ====== ", checkedField)
            return HttpResponseRedirect('home')
    except Exception as e:
        print("Exception =", e)
        return render(request, 'home.html')

Print Output:-

Checked list data ======  []

I’m working on a Django project where i want to do export in excel the selected data from checkbox.
Right now I’m able to do export into excel but getting all the data, instead i want the selected data which i will select from the checkbox.

Asked By: Iron Man

||

Answers:

  <form method="GET">
     <div class="form-row">
        <div class="custom-control custom-checkbox mb-10 popup-sec-chk">
            <input class="custom-control-input form-control inputfld" type="checkbox" id="date_inquiry" name="excelfields[]" value="dateofInquiry">
            <label class="custom-control-label" for="date_inquiry">Date of Inquiry</label>
        </div>
            
        <div class="custom-control custom-checkbox mb-10 popup-sec-chk">
            <input class="custom-control-input inputfld" type="checkbox" id="callers_name" name="excelfields[]" value="Callers name">
            <label class="custom-control-label" for="callers_name">Caller's Info</label>
        </div>
    </div>
    
    <div class="modal-footer">
        **<button type="submit" href="#" class="btn btn-primary" >Select</button>**
    </div>
  </form>

I just have to change the tag from a(anchor tag) to button and it worked for me.

Answered By: Iron Man
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.