django post checkbox data
I'm usin开发者_C百科g a checkbox form in my template and in my view im trying to check if the box has been checked or not I have the following code in my view:
if request.POST['check'] == True:
but then it throws an error if it is unchecked. How do i check if there is a value 'check' in my post data?
Thanks
The Python docs are your friend:
if request.POST.get('check', False):
...do stuff...
You could also do this (more Python docs):
if "check" in request.POST:
... do stuff...
This is what I did:
request.POST.get('field_name', '') == 'on'
Note: another proposed solution
request.POST.get('check', False) # do not use it
led to this error for me:
['“on” value must be either True or False.']
when the checkbox is selected.
精彩评论