Deluq Deluq - 10 months ago 113
HTML Question

How to trigger a function with checkbox django

I wanna know how I run certain functions depending on the selected checkboxes. This is my visual template:Template

and this is the code I have for my template is called admin.html:

<div class="panel-body">
<p><button type="button" class="btn btn-black"><i class="fa fa-upload" </i>&nbsp;&nbsp;<span class="bold">IMPORT ALL</span></button> </p>
<p> Import selected reports:</p>
<p> <label><input type="checkbox" value=""> Cisco Backlog Report</label></p>
<p> <label><input type="checkbox" value=""> Planning & Standard</label></p>
<p> <label><input type="checkbox" value=""> Emo Trans Report</label></p>
<p> <label><input type="checkbox" value=""> Phyllis Report</label></p>
<p> <label><input type="checkbox" value=""> Purchase Order View</label></p>
<p> <label><input type="checkbox" value=""> On Hand Inventory</label></p>
<p> <label><input type="checkbox" value=""> Bill of Material</label></p>
<p> <label><input type="checkbox" value=""> Aged</label></p>
<p> <label><input type="checkbox" value=""> Shipment with Times</label></p>
<p><button type="button" class="btn btn-danger">Import</button> </p>

As I mentioned before, I got 10 functions that read several .csv reports and upload the data into models and I trigger them with the URL section. In my I will show two examples:

def importpurchase(request)
Log logic here
def importcisco(request)
Log logic here
def importall(request) # this function is to import all

Answer Source

You can receive list of selected checkboxes using request.POST.getlist('mycheckboxname'), you should give your checkboxes name and value accordingly to selected field ('Aged' for example):

<input type="checkbox" name="mycheckboxname" value="Aged">

Then you can call any function depending on what selected in list:

def func1(l,vals):
  process_values_in_different_way(l, vals)...
def func2(l,vals):
 process_values(l, vals)...

def MyView(request):
 if 'Aged' in mylist:
    func2(mylist, values)
 elif anotherValue in mylist:
    func2(mylist, values)

EDIT(on your comments):

This is how django works: your client send request and you return response. This is called HTTP protocol. When IMPORT button is clicked your client send a form which contains all data entered by the user to the server. This data appears as a part of request object in your view. You can retrieve this data and you can do everything you want with this data. In my example process_values can, for example, select all 'Phyllis Report' objects and return them to response, as part of rendered template. There is no other way how you can do it. You cant just call on click function from server without request. To accomplish what you want you can try to split your logic and put part of it to javascript. You will be able to bound onclick listener to your button and then send requests through ajax to server. But this is a whole new story. This might be useful: ajax and django