Django: detect whether checkbox is submitted or disabled
-
29-05-2021 - |
题
In django, I have code to disable a checkbox dynamically, as unchecking it triggers some object deletion. If my object should not be deleted, the checkbox is rendered with disabled, and is not submitted.
However, in the view, I cannot distinguish between the checkbox being submitted as false and the checkbox not being submitted, as the form.cleaned_data still contains the key "is_user".
forms.py
if somecondition:
self.fields["is_user"].widget.attrs['disabled'] = True
views.py
if "is_user" in form.cleaned_data:
if form.cleaned_data["is_user"] == False:
do dangerous deleting
return redirect(page)
elif form.cleaned_data["is_user"] == True:
process information
return redirect(page)
else:
return redirect(page)
I submit the form from its checkbox-disabled state, and in the pdb shell I can type:
(pdb) form.cleaned_data
{'is_user': False}
I had expected form.cleaned_data not to contain a key for the non-submitted field. How can I detect whether it is not submitted, as opposed to submitted unchecked?
解决方案
There is no difference in HTML between a checkbox that is unchecked and one that is not submitted. Simply put, if you uncheck a checkbox, it is not included in the POST. This has nothing to do with Django, but is just how browsers work.
If you really need to distinguish between these states, you'll need a different control: perhaps a set of radio buttons for is_user
with true
and false
values. Alternatively, if you absolutely have to have a checkbox, perhaps you could use some Javascript to set a hidden control when it is unchecked.
In any case, having code that deletes unless a checkbox is ticked is very definitely the wrong way to go about it. Actions should always default to the least destructive: doing something like deleting requires a positive action.