How to send javascript list from template to request.POST (django framework)
I have the javascript below that gets all checked box and it works well.
<script>
function addlist() {
var array = []
var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')
for (var i = 0; i < checkboxes.length; i++) {
array.push(checkboxes[i].value);
}
document.write(array);
}
</script>
I want to know how to submit the list array list to views.py and get it via request.POST['']
Any suggestions?
I solved the question in the follow way:
I created a hidden input to receive the list by javascript:
<script>
function addlist() {
var array = []
var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')
for (var i = 0; i < checkboxes.length; i++) {
array.push(checkboxes[i].value);
}
document.getElementById('precedent_list').value = array;
}
</script>
<input type="hidden" style="outline-style: none;" id="precedent_list" name="precedent_list">
And I call the javascript function when the submit button is clicked:
<p class="w3-center" style="padding-top: 25px; padding-bottom: 25px">
<button class="w3-round-xxlarge general_button" type="submit" onclick="addlist()">Salvar</button>
</p>
In views.py I receive the list in the follow way:
my_list = ''
my_list_= []
if 'precedent_list' in request.POST:
my_list = request.POST['precedent_list']
my_list = my_list.replace(',',' ')
for j in my_list.split():
my_list_.append(int(j))