Django: detect whether checkbox is submitted or disabled

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".

if somecondition:
    self.fields["is_user"].widget.attrs['disabled'] = True

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)
    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.

Need Your Help

How does a web page knows when I interact with an element if it has no event handlers?

c# javascript browser

I was trying to use a WebBrowser to scrape this website and tried to programmatically change the amount of displayed pages to 200. If you manually change the value of the drop down menu, it will re...

C++ performance vs. Java/C#

c# java c++ performance bytecode

My understanding is that C/C++ produces native code to run on a particular machine architecture. Conversely, languages like Java and C# run on top of a virtual machine which abstracts away the nat...