(still unAnswered) django checkbox save yes or no in the database
Cited text taken from this source: https://docs.joomla.org/Talk:Checkbox_form_field_type
The same problem not only applies to the Joomla project but also to other web apps or websites using checkboxes (especially note the bold part).
Special care needs to be taken with saving an unchecked checkbox from a form!! This is a common mistake for component developers thinking Joomla takes care of this. Joomla doesn't, until now. (Problem in Joomla 2.5 still.)
You see, on saving a form with a checkbox that is unchecked, there is no variable for it in the POST data! So, it's quite common that the value will NOT be overwritten in your DB, especially if it is already on the value that represents "checked" (e.g. 1 ) on the form.
That's what the JavaScript snippet in your question is for.
// when page is ready
$(document).ready(function() {
// on form submit
$("#form").on('submit', function() {
// to each unchecked checkbox
$('input[type=checkbox]:not(:checked)').each(function() {
// set value 0 and check it
$(this).attr('checked', true).val(0);
})
})
})
I removed the $(this +
part because that breaks things.
To clarify: the script checks unchecked checkboxes (to make sure there is a checkbox being posted). But at the same time it changes the value when in checked
state to 0 (!)
So if you have unchecked boxes, they will represent 0's instead of being left out of POST request data. And when you have checked items yourself it leaves them alone and it will represent as a value of 1 within the POST data for the checkbox(es).
Duplicate ID's are also something you need to prevent. It's not valid HTML5.
Also you have this code:
request.POST['Asthma']
I've checked and found it returns a QueryDict
. Found that on this page:
https://docs.djangoproject.com/en/2.2/ref/request-response/#django.http.QueryDict
Example from that page:
QueryDict('a=1&a=2&c=3')
returns: <QueryDict: {'a': ['1', '2'], 'c': ['3']}>
This means that e.g. request.POST['Asthma']
would always return a list, which might be cast to a boolean type. So no matter what's in the list, it might cast to True
always.
So when you read on it says this:
QueryDict.__getitem__(key)¶
Returns the value for the given key. If the key has more than one value, it returns the last value.
So better use __getitem__(key)
or its alias here:
QueryDict.get(key, default=None)¶
Uses the same logic as getitem(), with a hook for returning a default value if the key doesn’t exist.
Of course, using the JavaScript snippet is one method you can use. But if you prefer to handle this in your Python code you can just use the QueryDict
like this:
Asthma = request.POST.get('Asthma', '0')