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

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?

Answers


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

Export Sql data to Excel very slow

c# sql-server-2008-r2 export export-to-excel

I am exporting Sql data to Excel. The code I am using currently is :

Select a record just if the one before it has a lower value takes too long and fail

mysql sql phpmyadmin

I've already asked 2 questions about this subject and got great answers on both of them.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.