There are two ways to solve this kind of issues, by keeping track of posted data in the Django view, or using ajax to send data to view, preventing html page and thus form to reload each time the post is sent.
1. Keeping track of posted data:
In your view, you should get checkbox states in the posted data, by getting list of checked values of your checkboxes and then return them as context data. It depends how your response is organized, but for simplicity let us assume you use TemplateResponse
:
return TemplateResponse(request, 'your.html',{'checked_hms':request.POST.getlist('hm')})
Than in your html you should use condition to check if value exists in checked_hms
and based on add checked
value to your checkbox inputs, like this:
...
<input type="checkbox" class="form-control" id="one" name="hm" value="one" {% if 'one' in checked_hms %}checked{% endif %} onchange="triggerPost()">
<label for="one">One</label>
<br>
<input type="checkbox" class="form-control" id="two" name="hm" value="two" {% if 'two' in checked_hms %}checked{% endif %} onchange="triggerPost()">
<label for="two">Two</label>
...
2. Using ajax:
You may send form data as post, using ajax call, which will not reload form, thus keeping checkboxes states intact, something like this:
<script>
function triggerPost() {
$.ajax({
type: "POST",
url: $('#hostform').attr('action'),
data: $('#hostform').serialize()
});
};
</script>